首页 文章

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

提问于
浏览
467

Go有类似于python的多行字符串:

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

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

8 回答

  • 30

    你必须非常小心格式和行间距,一切都很重要,这里是一个工作样本,试试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)
    }
    
  • 763

    来自String literals

    • 原始字符串文字支持多行(但不解释转义字符)

    • 解释字符串文字解释转义字符,如' \n ' .

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

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

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

    + "`" + ...
    
  • 18

    Go和多行字符串

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

    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并进行实验 .

  • 3

    你可以写:

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

    这与:

    "line 1line 2line3"
    

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

    "line 1"
    +"line 2"
    

    生成错误 .

  • 2

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

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

    原始字符串文字

    原始字符串文字是后引号之间的字符序列,如foo中所示 . 在引号内,除反向引号外,任何字符都可能出现 .

    一个重要的部分是 raw literal不仅仅是多行而且多行并不是它的唯一目的 .

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

    所以逃避不会被解释和 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)
    }
    

    连接

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

    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
    }
    
  • 4

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

    var hi = `I am here,
    hello,
    `
    
  • 4

    你可以使用原始文字 . 例

    s:=`stack
    overflow`
    
  • 77

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

    `line 1
    line 2
    line 3`
    

相关问题