我在 fmt.Sprintf 中有很长的一行。如何在代码中拆分它?我不想将所有内容都放在一行中,因此代码看起来很难看。
fmt.Sprintf("a:%s, b:%s ...... this goes really long")
Use string concatenation to construct a single string value on multiple lines:
fmt.Sprintf("a:%s, b:%s " +
" ...... this goes really long",
s1, s2)
The long string in this example is built at compile time because the string concatenation is a constant expression.
You can split the string at contained newlines using a raw string literal:
fmt.Sprintf(`this text is on the first line
and this text is on the second line,
and third`)
您还可以在反引号内使用原始字符串文字,如下所示:
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"
.
Why don't you split it out:
fmt.Sprintf("a:%s, b:%s ", x1, x2)
fmt.Sprintf("...... ")
fmt.Sprintf("this goes really long")
Or you can split them out with the plus sign as indicated by 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")
}