如何在golang中将变量参数传递给Sprintf函数

huangapple go评论85阅读模式
英文:

How to pass variable parameters to Sprintf in golang

问题

我懒得一个一个传递变量给Printf函数,有没有办法一次性传递多个变量?(示例代码简化为3个参数,我需要超过10个参数)。

我得到了以下错误信息:

> cannot use v (type []string) as type []interface {} in argument to fmt.Printf

s := []string{"a", "b", "c", "d"}  // 从regexp.FindStringSubmatch()得到的结果
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])  

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)  
英文:

I'm lazy, want to pass many variables to Printf function, is it possible?
(The sample code is simplified as 3 parameters, I require more than 10 parameters).

I got the following message:

> cannot use v (type []string) as type []interface {} in argument to fmt.Printf

s := []string{"a", "b", "c", "d"}  // Result from regexp.FindStringSubmatch()
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])  

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)  

答案1

得分: 14

是的,这是可能的,只需将你的切片声明为[]interface{}类型,因为这是Printf()所期望的类型。Printf()的签名如下:

func Printf(format string, a ...interface{}) (n int, err error)

所以这样可以工作:

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)

输出结果(Go Playground):

b    c   d
b    c   d

[]interface{}[]string是不可转换的。查看这个问题+答案以获取更多详细信息:

https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go

如果你已经有一个[]string或者你使用一个返回[]string的函数,你需要手动将其转换为[]interface{},像这样:

ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}
英文:

Yes, it is possible, just declare your slice to be of type []interface{} because that's what Printf() expects. Printf() signature:

func Printf(format string, a ...interface{}) (n int, err error)

So this will work:

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)

Output (Go Playground):

b    c   d
b    c   d

[]interface{} and []string are not convertible. See this question+answers for more details:

https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go

If you already have a []string or you use a function which returns a []string, you have to manually convert it to []interface{}, like this:

ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}

huangapple
  • 本文由 发表于 2015年6月2日 14:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/30588581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定