在不打印的情况下格式化 Go 字符串? [英] Format a Go string without printing?

查看:30
本文介绍了在不打印的情况下格式化 Go 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a simple way to format a string in Go without printing the string?

我能做到:

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

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

But I want the formatted string returned rather than printed so I can manipulate it further.

我也可以这样做:

s := "foo: " + bar

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

But this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like

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

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

Is there a simpler way to do this?

推荐答案

Sprintf 是什么您正在寻找.

示例

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

您还可以在A Tour of去."

You can also see it in use in the Errors example as part of "A Tour of Go."

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

这篇关于在不打印的情况下格式化 Go 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆