你如何在Go中编写多行字符串?

问题描述 投票:523回答:8

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

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

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

string go multiline
8个回答
866
投票

根据language specification,您可以使用原始字符串文字,其中字符串由反引号而不是双引号分隔。

`line 1
line 2
line 3`

94
投票

你可以写:

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

这与:

"line 1line 2line3"

与使用后退标记不同,它将保留转义字符。请注意,“+”必须位于“前导”行,即:

"line 1"
+"line 2"

生成错误。


34
投票

来自String literals

  • 原始字符串文字支持多行(但不解释转义字符)
  • 解释字符串文字解释转义字符,如'\n'。

但是,如果你的多行字符串必须包含一个反引号(`),那么你将不得不使用一个解释的字符串文字:

`line one
  line two ` +
"`" + `line three
line four`

你不能直接将反引号(`)放在原始字符串文字(``xx\)中。 你必须使用(如“how to put a backquote in a backquoted string?”中所述):

 + "`" + ...

23
投票

将原始字符串文字用于多行字符串:

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

Raw string literals

原始字符串文字是后引号之间的字符序列,如`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)
}

Concatenation

可能你想要打破你的长行,你不需要新行。在这种情况下,您可以使用字符串连接。

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
}

7
投票

去和多线字符串

使用后退标记,您可以使用多行字符串:

package main

import "fmt"

func main() {

    message := `This is a 
Multi-line Text String
Because it uses the raw-string back ticks 
instead of quotes.
`

    fmt.Printf("%s", message)
}

而不是使用双引号(“)或单引号符号('),而是使用反向标记来定义字符串的开头和结尾。然后,您可以跨行包装它。

如果你缩进字符串,请记住空白区域将被计算。

请检查playground 并进行实验。


4
投票

你可以把内容放在它周围,比如说

var hi = `I am here,
hello,
`

3
投票

你必须非常小心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)
}

1
投票

你可以使用原始文字。例

s:=`stack
overflow`

0
投票

对我来说,如果添加\n不是问题,这就是我使用的。

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

否则你可以使用raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `
© www.soinside.com 2019 - 2024. All rights reserved.