fmt.Sprintf传递参数数组 [英] fmt.Sprintf passing an array of arguments

查看:237
本文介绍了fmt.Sprintf传递参数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,基本的问题。我想传递一个片段作为 fmt.Sprintf 的参数。就像这样:

  values:= [] string {foo,bar,baz} 
结果:= fmt.Sprintf(%s%s%s,values ...)

结果会是 foobarbaz ,但这显然不起作用。



格式比这更复杂,所以一个简单的连接不会这样做)



所以问题是:如果我有数组,那么我怎样才能把它作为将参数分隔到 fmt.Sprintf ?或者:我可以调用一个函数传递一个参数列表?

解决方案

当你在IRC上发现,这将工作:

$ p $ values:= [] interface {} {foo,bar,baz}
结果:= fmt.Sprintf(%s%s%s,values ...)

您的原始代码不起作用,因为 fmt.Sprintf 接受 []界面{} [] string 无法隐式或显式地转换为该类型。


Sorry for the basic question. I'd like to pass a slice as arguments to fmt.Sprintf. Something like this:

values := []string{"foo", "bar", "baz"}
result := fmt.Sprintf("%s%s%s", values...)

And the result would be foobarbaz, but this obviously doesn't work.

(the string I want to format is more complicated than that, so a simple concatenation won't do it :)

So the question is: if I have am array, how can I pass it as separated arguments to fmt.Sprintf? Or: can I call a function passing an list of arguments in Go?

解决方案

As you found out on IRC, this will work:

values := []interface{}{"foo", "bar", "baz"}
result := fmt.Sprintf("%s%s%s", values...)

Your original code doesn't work because fmt.Sprintf accepts a []interface{} and []string can't be converted to that type, implicitly or explicitly.

这篇关于fmt.Sprintf传递参数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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