对多行字符串使用原始字符串文字:

func main(){
    multiline := `line 
by line
and line
after line`
}

原始字符串文字

`foo`

一个重要的部分是原始文字不只是多行,而且成为多行并不是其唯一目的。

原始字符串文字的值是由引号之间未解释(隐式为UTF-8编码)字符组成的字符串。特别是反斜杠没有特殊含义...

因此,转义符将不会被解释,刻度线之间的新行将是真正的新行

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)
}

级联

可能您有长行要中断,并且不需要新行。在这种情况下,您可以使用字符串连接。

func main(){
    multiline := "line " +
            "by line " +
            "and line " +
            "after line"

    fmt.Print(multiline) // No new lines here
}

由于“”被解释为字符串,因此将解释字面量转义。

func main(){
    multiline := "line " +
            "by line \n" +
            "and line \n" +
            "after line"

    fmt.Print(multiline) // New lines as interpreted \n
}