Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write multiline strings in Go?

Does Go have anything similar to Python's multiline strings:

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

If not, what is the preferred way of writing strings spanning multiple lines?

like image 527
aeter Avatar asked Oct 28 '11 18:10

aeter


People also ask

What are the two ways to write a multiline string?

Three single quotes, three double quotes, brackets, and backslash can be used to create multiline strings. Whereas the user needs to mention the use of spaces between the strings.

How do I add a new line to a string in Golang?

A string in memory can contain as many '\n' characters as you like. The string "foo\nbar\n" , when written to a text file, will create two lines, "foo" and "bar" .

Can a string be multiple lines?

Raw StringsThey can span multiple lines without concatenation and they don't use escaped sequences. You can use backslashes or double quotes directly.


2 Answers

According to the language specification you can use a raw string literal, where the string is delimited by backticks instead of double quotes.

`line 1 line 2 line 3` 
like image 156
Mark Byers Avatar answered Sep 29 '22 06:09

Mark Byers


You can write:

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

which is the same as:

"line 1line 2line 3" 

Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line - for instance, the following will generate an error:

"line 1" +"line 2" 
like image 43
mddkpp at gmail.com Avatar answered Sep 29 '22 07:09

mddkpp at gmail.com