fmt.Sprintf passing an array of arguments

2019-04-04 23:14发布

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?

标签: format go
2条回答
可以哭但决不认输i
2楼-- · 2019-04-04 23:46

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.

查看更多
Deceive 欺骗
3楼-- · 2019-04-04 23:52

I think the issue with doing this is that the Sprintf won't work with unbounded length slices, so it's not practical. The number of format parameters must match the number of formatting directives. You will either have to extract them into local variables or write something to iterate the slice and concatenate the strings together. I'd go for the latter.

查看更多
登录 后发表回答