【问题标题】:how to split long lines for fmt.sprintf如何拆分 fmt.sprintf 的长行
【发布时间】:2016-02-01 23:41:30
【问题描述】:

我在 fmt.Sprintf 中有很长的一行。如何在代码中拆分它?我不想将所有内容都放在一行中,这样代码看起来很难看。

fmt.Sprintf("a:%s, b:%s  ...... this goes really long")

【问题讨论】:

    标签: go gofmt


    【解决方案1】:

    使用string concatenation 在多行上构造单个字符串值:

     fmt.Sprintf("a:%s, b:%s " +
        " ...... this goes really long",
        s1, s2)
    

    此示例中的长字符串是在编译时构建的,因为字符串连接是一个常量表达式。

    您可以使用raw string literal 在包含的换行符处拆分字符串:

         fmt.Sprintf(`this text is on the first line
    and this text is on the second line,
    and third`)
    

    【讨论】:

      【解决方案2】:

      您也可以在反引号内使用raw string literals,如下所示:

      columns := "id, name"
      table := "users"
      query := fmt.Sprintf(`
          SELECT %s
          FROM %s
        `, columns, table)
      fmt.Println(query)
      

      这种方法有一些注意事项:

      1. 原始字符串不解析转义序列
      2. 所有的空格都将被保留,因此在此查询中的FROM 子句之前会有一个换行符和几个制表符。

      这些问题对某些人来说可能是一个挑战,并且空格会产生一些难看的结果字符串。但是,我更喜欢这种方法,因为它允许您将长而复杂的 SQL 查询复制并粘贴到代码之外并粘贴到其他上下文中,例如用于测试的 sql 工作表。

      【讨论】:

        【解决方案3】:

        由于您已经在使用Sprintf(这意味着您将有一个类似“这是其中包含 %s 占位符的字符串”的字符串),您可以在字符串中添加更多占位符,然后将您的值'想在自己的台词那里喜欢;

        fmt.Sprintf("This %s is so long that I need %s%s%s for the other three strings,
        "string",
        "some super long statement that I don't want to type on 50 lines",
        "another one of those",
        "yet another one of those")
        

        另一种选择是使用字符串连接,如"string 1" + "string 2"

        【讨论】:

        • 似乎最好将字符串连接起来,以便在编译时而不是像上面那样在运行时构建长字符串。 (除非以某种方式进行了优化。)
        • @AndySchweig 我不确定 Go 编译器做了哪些优化,但是没有理由不能像连接一样优化。同样的规则适用,如果在编译时所有值都已知,则可以进行计算,如果直到运行时才知道一个或多个值,则不能。
        【解决方案4】:

        你为什么不把它分开:

        fmt.Sprintf("a:%s, b:%s ", x1, x2)
        
        fmt.Sprintf("...... ")
        
        fmt.Sprintf("this goes really long")
        

        或者您可以使用 MuffinTop 所示的加号将它们分开。

        【讨论】:

          【解决方案5】:

          另一个选项是strings.Builder:

          package main
          
          import (
             "fmt"
             "strings"
          )
          
          func main() {
             b := new(strings.Builder)
             fmt.Fprint(b, "North")
             fmt.Fprint(b, "South")
             println(b.String() == "NorthSouth")
          }
          

          https://golang.org/pkg/strings#Builder

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-08
            相关资源
            最近更新 更多