本文翻译自:How do you write multiline strings in Go?
Does Go have anything similar to Python's multiline strings: Go是否与Python的多行字符串相似?
"""line 1
line 2
line 3"""
If not, what is the preferred way of writing strings spanning multiple lines? 如果不是,编写跨多行字符串的首选方式是什么?
参考:https://stackoom.com/question/XHr2/如何在Go中编写多行字符串
From String literals : 从字符串文字 :
\\n
'. 解释的字符串文字解释转义的字符,例如' \\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 \\
). 您不能在原始字符串文字(``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`
. 原始字符串文字是反引号之间的字符序列,如`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; 原始字符串文字的值是由引号之间未解释(隐式为UTF-8编码)的字符组成的字符串。 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 您必须非常注意格式和行间距,一切都很重要,这是一个有效的示例,请尝试一下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`