【发布时间】:2016-02-01 23:41:30
【问题描述】:
我在 fmt.Sprintf 中有很长的一行。如何在代码中拆分它?我不想将所有内容都放在一行中,这样代码看起来很难看。
fmt.Sprintf("a:%s, b:%s ...... this goes really long")
【问题讨论】:
我在 fmt.Sprintf 中有很长的一行。如何在代码中拆分它?我不想将所有内容都放在一行中,这样代码看起来很难看。
fmt.Sprintf("a:%s, b:%s ...... this goes really long")
【问题讨论】:
使用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`)
【讨论】:
您也可以在反引号内使用raw string literals,如下所示:
columns := "id, name"
table := "users"
query := fmt.Sprintf(`
SELECT %s
FROM %s
`, columns, table)
fmt.Println(query)
这种方法有一些注意事项:
FROM 子句之前会有一个换行符和几个制表符。这些问题对某些人来说可能是一个挑战,并且空格会产生一些难看的结果字符串。但是,我更喜欢这种方法,因为它允许您将长而复杂的 SQL 查询复制并粘贴到代码之外并粘贴到其他上下文中,例如用于测试的 sql 工作表。
【讨论】:
由于您已经在使用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"。
【讨论】:
你为什么不把它分开:
fmt.Sprintf("a:%s, b:%s ", x1, x2)
fmt.Sprintf("...... ")
fmt.Sprintf("this goes really long")
或者您可以使用 MuffinTop 所示的加号将它们分开。
【讨论】:
另一个选项是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")
}
【讨论】: