Question

How to Write Multiline Strings in Go

gostringmultiline

Question

In Go, is there anything similar to Python's multiline string syntax?

"""line 1
line 2
line 3"""

If not, what is the preferred way to write strings that span multiple lines in Go?

Short Answer

By the end of this page, you will understand how Go represents multiline strings, when to use raw string literals versus interpreted string literals, how newlines are preserved, and what patterns developers commonly use in real Go programs.

Concept

In Go, multiline strings are usually written with raw string literals, which use backticks:

text := `line 1
line 2
line 3`

This is the closest equivalent to Python's triple-quoted strings for many use cases.

Go has two main kinds of string literals:

  • Interpreted string literals: wrapped in double quotes ("...")
  • Raw string literals: wrapped in backticks (`...`)

Interpreted string literals

These process escape sequences such as:

  • \n for newline
  • \t for tab
  • \" for a quote

Example:

text := "line 1\nline 2\nline 3"

Raw string literals

These keep the text almost exactly as written, including line breaks.

Example:

text := `line 1
line 2
line 3`

This matters because in real programs, developers often need to store:

  • SQL queries
  • JSON samples
  • HTML templates
  • command output examples
  • test data
  • help text and CLI messages

Raw string literals make multiline content easier to read and maintain.

Mental Model

Think of Go strings as having two writing modes:

  • Double quotes are like a text editor that understands special shortcuts. If you type \n, Go turns it into a real newline.
  • Backticks are like a glass box around your text. Go keeps what you typed almost exactly as it appears.

So if you want to write a paragraph or block of text exactly as it looks on the screen, backticks are usually the simplest choice.

Take Quiz

Syntax and Examples

Core syntax

Raw string literal

message := `line 1
line 2
line 3`

This creates a string containing actual line breaks.

Interpreted string literal

message := "line 1\nline 2\nline 3"

This also creates a multiline string, but the newlines are added using escape sequences.

Beginner-friendly examples

Example 1: Using backticks for multiline text

package main

import "fmt"

func main() {
    text := `Hello,
This is a multiline string in Go.
Goodbye.`

    fmt.Println(text)
}

Why this works

  • The string starts and ends with backticks.
  • The line breaks inside the string are preserved.
  • This is usually the cleanest way to write readable multiline text.

Example 2: Using double quotes with \n

package main

import "fmt"

func main() {
    text := "Hello,\nThis is a multiline string in Go.\nGoodbye."
    fmt.Println(text)
}

When to use this version

Use double quotes when you need escape sequences such as:

  • \n
  • \t
  • unicode escapes
  • embedded backticks are not possible in a raw string

Example 3: A multiline SQL query

query := `SELECT id, name
FROM users
WHERE active = true
ORDER BY name`

This is much easier to read than one long line.

Step by Step Execution

Consider this example:

package main

import "fmt"

func main() {
    message := `line 1
line 2`
    fmt.Println(message)
}

Step by step

  1. Go sees the backtick at the start of the string.
  2. It treats everything until the closing backtick as raw text.
  3. The newline between line 1 and line 2 becomes part of the string.
  4. The variable message stores a string with two lines.
  5. fmt.Println(message) prints the string.
  6. fmt.Println also adds its own newline after printing.

Output

line 1
line 2

Now compare it with this:

message := "line 1\nline 2"

What happens here

  1. Go sees double quotes, so this is an interpreted string.
  2. It reads \n as a newline character.
  3. The final stored string is still two lines.
  4. The result when printed is the same.

The main difference is how you write the string in source code, not the final value.

Real World Use Cases

Multiline strings are useful in many real Go programs.

Common uses

SQL queries

query := `SELECT id, email
FROM customers
WHERE subscribed = true`

This keeps complex queries readable.

JSON examples or test payloads

payload := `{
  "name": "Ava",
  "active": true
}`

Or, if you want the formatting exactly as written:

payload := `{
  "name": "Ava",
  "active": true
}`

A more natural raw string version would be:

payload := `{
  "name": "Ava",
  "active": true
}`

In practice, developers often write actual formatted JSON with real newlines in a raw string.

CLI help messages

help := `Usage:
  app serve
  app version

Options:
  --port    Port number`

Templates and sample content

email := `Hello {{.Name}},

Your order has shipped.

Thanks!`

Test fixtures

Large expected outputs are often easier to compare when written as multiline strings.

Take Quiz

Real Codebase Usage

In real codebases, developers usually choose between backticks and double quotes based on readability and needed features.

Common patterns

1. Raw strings for readable blocks of text

Used for:

  • SQL
  • HTML fragments
  • sample API responses
  • test fixtures
  • documentation text
const helpText = `Usage:
  tool run
  tool test`

2. Double quotes when escapes are needed

If you need special characters or precise control, interpreted strings are often better.

path := "C:\\temp\\file.txt"

3. Concatenation for dynamic content

Static multiline text is often combined with variables.

name := "Sam"
message := "Hello, " + name + "\nWelcome back."

4. Formatting with fmt.Sprintf

Useful when a multiline string includes values.

report := fmt.Sprintf("User: %s\nStatus: %s", name, status)

5. Constants for repeated text

Large multiline text blocks are often stored as constants for reuse.

const banner = `My App
Version 1.0`

The main goal in production code is usually clarity. If backticks make the text easier to read, use them.

Common Mistakes

1. Expecting Python triple quotes in Go

Go does not use """...""" for strings.

Incorrect

text := """line 1
line 2"""

Correct

text := `line 1
line 2`

2. Forgetting that raw strings preserve formatting exactly

Extra spaces and indentation become part of the string.

text := `line 1
    line 2`

That indentation is stored too.

3. Trying to use escape sequences inside raw strings

In a raw string, \n is usually treated as the characters backslash and n, not a special escape.

Broken expectation

text := `hello\nworld`
fmt.Println(text)

This prints:

hello\nworld

Use this instead

text := "hello\nworld"

Or write an actual newline in the raw string.

4. Trying to include a backtick inside a raw string

Raw strings cannot directly contain backticks.

Problem

text := `Use the ` + "`go run`" + ` command`

If you need backticks in the content, use double quotes or concatenation carefully.

5. Unwanted leading newline

This often happens when the content starts on the next line.

text := `
line 1
line 2`

That first blank line is part of the string.

To avoid it, start the content immediately after the opening backtick when needed.

Comparisons

Raw strings vs interpreted strings in Go

FeatureRaw string literalInterpreted string literal
DelimiterBackticksDouble quotes
Multiline supportYes, naturallyYes, using \n or line continuation through concatenation
Escape sequences processedNoYes
Best for readable blocks of textYesSometimes
Can easily include double quotesYesMust escape them
Can include backticks directlyNoYes

Which should you choose?

SituationBetter choice
Writing a multiline SQL queryRaw string
Writing text exactly as it appearsRaw string
Needing \n, \t, or unicode escapesInterpreted string
String contains backticksInterpreted string
Building a string with variablesInterpreted string with fmt.Sprintf or concatenation

The key idea is simple: use raw strings for readability, and use interpreted strings when you need escapes or special formatting behavior.

Take Quiz

Cheat Sheet

Quick reference

Raw string literal

text := `line 1
line 2`
  • Uses backticks
  • Can span multiple lines
  • Preserves line breaks
  • Does not process most escape sequences

Interpreted string literal

text := "line 1\nline 2"
  • Uses double quotes
  • Escape sequences work
  • Good when you need \n, \t, \", or unicode escapes

Rules to remember

  • Go does not use Python-style triple quotes.
  • Backticks are the usual way to write multiline string literals.
  • Raw strings keep spaces and indentation.
  • Raw strings cannot directly contain backticks.
  • Double-quoted strings are better when escape sequences are required.

Common patterns

const message = `Hello
World`
message := fmt.Sprintf("Name: %s\nStatus: %s", name, status)

Edge cases

  • A newline immediately after the opening backtick becomes part of the string.
  • \n inside a raw string is usually just two characters.
  • fmt.Println adds its own newline after printing.

FAQ

Is there a multiline string syntax in Go like Python triple quotes?

No. Go uses raw string literals with backticks instead of triple quotes.

What is the preferred way to write multiline strings in Go?

Usually, use a raw string literal with backticks because it is the most readable for multiline text.

Can Go strings span multiple lines with double quotes?

Yes, but usually by using \n escape sequences or concatenating strings. Raw strings are often cleaner for literal multiline text.

Do raw strings preserve indentation in Go?

Yes. Any spaces and tabs you include are stored in the string.

Can I use escape sequences like \n inside a raw string?

Not in the usual interpreted way. In a raw string, the characters are mostly kept as written.

Can a raw string contain backticks?

Not directly. If your content includes backticks, use a double-quoted string or build the string from parts.

Which is better for SQL queries in Go?

Raw strings are often better because they keep the query readable across multiple lines.

Take Quiz

Mini Project

Description

Build a small Go program that prints a command-line help message using a multiline string. This demonstrates the most common beginner-friendly use of raw string literals: storing readable text exactly as it should appear to the user.

Goal

Create a Go program that stores and prints a formatted multiline help message using a raw string literal.

Requirements

  • Define a multiline help message in a variable using backticks.
  • Include at least a title, a usage section, and an options section.
  • Print the message to the terminal with fmt.Println.
  • Make sure the output formatting is easy to read.
Take Quiz

Keep learning

Related questions

View more