How do you write multiline strings in Go?

By Mike Sallese ·

Jump right to the example

Multiline strings vs regular strings

Normally in Go, we’ll create a string with double quotes:

myString := "this is a string"

To have a string span multiple lines, we could use \n like so:

uglyMultilineString := "This is line one.\nThis is line two.\nThis is line three."

While this does work, it’s really ugly. It also is a nightmare if you have to copy and paste a multiline string that doesn’t have the \n’s already included.

Luckily, Go has a better solution.

Multiline string example

Go made it really easy to create a multiline string. To create a multiline string, simply use backticks instead of quotes:

multiLineString := `
This is line one.
This is line two.
This is line three.
`

fmt.Println(multiLineString)
// output:
// This is line one.
// This is line two.
// This is line three.

For other Golang examples: https://www.mikesallese.me/tags/golang

About the author

Mike Sallese. I build Scribbl, an AI note taker with no bot in the call, and a few other pieces of software. Off the computer I am building a straw bale workshop.

X · Medium · GitHub · articles on other sites