Golang:格式化字符串而不打印? [英] Golang: format a string without printing?

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

问题描述



我可以这样做:



是否有一种简单的方法在Go中格式化字符串而不打印字符串?

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

但是我想要格式化的字符串返回而不是打印,所以我可以进一步操纵它。



我也可以做例如:

  s:=foo:+ bar 

但是,当格式字符串很复杂时,这会变得难以理解,而且当一个或多个部分不是字符串时必须先转换, / p>

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

我非常喜欢Go,我的背景是Ruby,在这里很简单。有没有一个更简单的方法来做到这一点?

Sprintf

这里也是在教程Go to Go中的一个用法。

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


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

I can do:

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

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

I could also do something like:

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)

I'm very new to Go - my background is in Ruby, where this is straightforward. Is there a simpler way to do this?

解决方案

Sprintf

Here also is a use of it in the tutorial, "A Tour of Go."

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

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

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