How to Create Multiline Strings in Go
When you want a string to span multiple lines, using an interpreted string
literal with the \n
character slotted in at multiple points can be extremely
tedious and hard to read. I mean, just take a look at this:
str := "I\nam\na\nmultiline\nstring"
fmt.Println(str)
This is where raw string literals come in handy. They are enclosed in back ticks and are displayed exactly as they are written in the source code making them the go-to solution for multiline strings in Go.
str := `I
am
a
multiline
string`
fmt.Println(str)
As you can see, the output from both snippets is exactly the same, but the latter is significantly easier to write and read.
Note that escape characters such as \n
, \t
and others are not supported in
raw string literals due to the fact that they are left uninterpreted. Everything
will be as defined in the source code including any spacing used for
indentation.
For example, here’s some HTML boilerplate:
str := `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script></script>
</body>
</html>.`
fmt.Println(str)
Notice how the output preserves the indentation as specified in the source code:
You can find more information about both interpreted and raw string literals in the language specification.
Thanks for reading, and happy coding!