Does Go have anything similar to the python's multiline strings:
"""line 1
line 2
line 3"""
If not, what is the preferred way of writing strings spanning multiple lines?
转载于:https://stackoverflow.com/questions/7933460/how-do-you-write-multiline-strings-in-go
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`
You can write:
"line 1" +
"line 2" +
"line 3"
which is the same as:
"line 1line 2line3"
Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line i.e.:
"line 1"
+"line 2"
generates an error.
From String literals:
\n
'.But, if your multi-line string has to include a backquote (`), then you will have to use an interpreted string literal:
`line one
line two ` +
"`" + `line three
line four`
You cannot directly put a backquote (`) in a raw string literal (``xx\
).
You have to use (as explained in "how to put a backquote in a backquoted string?"):
+ "`" + ...
You can put content with `` around it, like
var hi = `I am here,
hello,
`
Use raw string literals for multi-line strings:
func main(){
multiline := `line
by line
and line
after line`
}
Raw string literals are character sequences between back quotes, as in
foo
. Within the quotes, any character may appear except back quote.
A significant part is that is raw literal not just multi-line and to be multi-line is not the only purpose of it.
The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning...
So escapes will not be interpreted and new lines between ticks will be real new lines.
func main(){
multiline := `line
by line \n
and line \n
after line`
// \n will be just printed.
// But new lines are there too.
fmt.Print(multiline)
}
Possibly you have long line which you want to break and you don't need new lines in it. In this case you could use string concatenation.
func main(){
multiline := "line " +
"by line " +
"and line " +
"after line"
fmt.Print(multiline) // No new lines here
}
Since " " is interpreted string literal escapes will be interpreted.
func main(){
multiline := "line " +
"by line \n" +
"and line \n" +
"after line"
fmt.Print(multiline) // New lines as interpreted \n
}
You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF
package main
import "fmt"
func main() {
testLine := `This is a test line 1
This is a test line 2`
fmt.Println(testLine)
}
you can use raw literals. Example
s:=`stack
overflow`