gpt4 book ai didi

string - 格式化 Go 字符串而不打印?

转载 作者:bug小助手 更新时间:2023-10-28 10:41:51 25 4
gpt4 key购买 nike

有没有一种简单的方法可以在不打印字符串的情况下在 Go 中格式化字符串?

我能做到:

bar := "bar"
fmt.Printf("foo: %s", bar)

但我希望返回格式化的字符串而不是打印出来,以便进一步操作它。

我也可以这样做:

s := "foo: " + bar

但是当格式字符串很复杂时,这变得难以阅读,当一个或多个部分不是字符串并且必须首先转换时,这变得很麻烦,例如

i := 25
s := "foo: " + strconv.Itoa(i)

有没有更简单的方法来做到这一点?

最佳答案

Sprintf就是你要找的。

示例

fmt.Sprintf("foo: %s", bar)

您还可以在 Errors example 中看到它的使用情况。作为“围棋之旅”的一部分。

return fmt.Sprintf("at %v, %s", e.When, e.What)

关于string - 格式化 Go 字符串而不打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11123865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com