英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论