How to write multiline string in Go (Golang)

How to write multiline string in Go (Golang)

You might have used multiline string notation in other languages before, but in this article we are going to explore how to write multiline strings in Go (Golang). The Go (Golang) standard library offers almost everything you need and also in this case it will just be enough to use built-in functionality to write multiline strings in Go.

If you look closely at the language specification, in particular in the string literals documentation you will see the following:

There are two forms: raw string literals and interpreted string literals.

So strings in Go can be expressed in two ways: Raw String Literals and Intepreted String Literals. Let's see what the difference is

Interpreted String Literals

Based on the official documentation here's the definition of Interpreted String Literals:

Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear except newline and unescaped double quote

Raw string literals

Based on the official documentation here's the definition of Raw String Literals:

Raw string literals are character sequences between back quotes, as in `foo`. Within the quotes, any character may appear except back quote [...] in particular, backslashes have no special meaning and the string may contain newlines

So Raw String literals is what we are going to use.

Using Raw String Literals to write multiline strings in Go (Golang)

To use a Raw String Literal it's enough to use the backquote ` character.

package main

import "fmt"

func main() {
    name := "Bob"
	text := `Hi %s
this is a
text composed of
multiline strings
`
	fmt.Printf(text, name)
}

And here's the expected output

Hi Bob
this is a
text composed of
multiline strings

Check out this code snipped on the Go Playground https://go.dev/play/p/zYTueyWdQlc

Join the Golang Developers Community on Golang Cafe