为什么要使用fmt.Sprint?

J. *_*Eng 8 go

fmt.Sprint与添加字符串相比,我真的不明白使用的好处+.以下是两个使用中的示例:

func main() {
    myString := fmt.Sprint("Hello", "world")
    fmt.Println(myString)
}
Run Code Online (Sandbox Code Playgroud)

func main() {
    myString := "Hello " + "World"
    fmt.Println(myString)
}
Run Code Online (Sandbox Code Playgroud)

每个的差异和好处是什么?

Erw*_*win 13

在你的例子中没有真正的差异,因为你是Sprintf简单地连续字符串.这确实可以通过使用'+'运算符更容易地解决.

采用以下示例,您要在其中打印清除错误消息,例如"找不到ID为'42的产品'.".你的底层方法看起来如何?

productID := 42;
myString := "Product with ID '" + productID + "' could not be found."
Run Code Online (Sandbox Code Playgroud)

这会产生错误(类型字符串和int不匹配),因为Go不支持将不同类型连接在一起.

所以你必须先将类型转换为字符串.

productID := 42
myString := "Product with ID '" + strconv.Itoa(productID) + "' could not be found."
Run Code Online (Sandbox Code Playgroud)

而且,除了字符串之外,您还必须为每种数据类型执行此操作.

fmtGo中的包和几乎任何其他语言的类似格式化包解决了这个问题,它帮助您进行转换并使您的字符串远离大量"+"运算符.

以下是该示例的使用方式 fmt

product := 42
myString := fmt.Sprintf("Product with ID '%d' could not be found.", product)
Run Code Online (Sandbox Code Playgroud)

%d是'将参数打印为数字'的格式化动词.请参阅https://golang.org/pkg/fmt/#hdr-打印其他各种打印方式.

与连接相比,fmt允许您以清晰的方式编写字符串,将模板/文本与变量分开.而且,它简化了字符串以外的打印数据类型.

  • @Sathesh `fmt.Printf()` 打印字符串,而 `fmt.Sprintf()` 创建一个字符串并返回它。完全不同的东西 (7认同)
  • 这个问题里没有Sprintf,都是关于Sprint的 (4认同)

Wis*_*ter 6

fmt.Sprint非常适合连接不同类型的参数,因为它在底层使用反射。因此,如果您需要连接字符串 - 使用“ + ”,它会快得多,但如果您需要联系号码和您的利润fmt.Sprint就像这样:

message := fmt.Sprint(500, "internal server error")
Run Code Online (Sandbox Code Playgroud)