Go是否有类似于Python的多行字符串:

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

如果没有,那么编写跨多行字符串的首选方式是什么?


当前回答

你可以写:

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

其与:

"line 1line 2line 3"

与使用反引号不同,它将保留转义字符。请注意,“+”必须在“前导”行上-例如,以下内容将生成错误:

"line 1"
+"line 2"

其他回答

可以使用原始文字。实例

s:=`stack
overflow`

根据语言规范,可以使用原始字符串文本,其中字符串由反引号而不是双引号分隔。

`line 1
line 2
line 3`

对我来说,如果添加不成问题,这就是我使用的方法。

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

否则,可以使用原始字符串

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `

在go中,你必须非常小心格式和行距,一切都很重要,这里有一个工作示例,请尝试一下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)
}

你可以写:

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

其与:

"line 1line 2line 3"

与使用反引号不同,它将保留转义字符。请注意,“+”必须在“前导”行上-例如,以下内容将生成错误:

"line 1"
+"line 2"