我很懒,想将许多变量传递给Printf
函数,可以吗?
(示例代码简化为3个参数,我需要10个以上的参数)。
我收到以下消息:
fmt.Printf的参数中不能使用v(类型[] string)作为类型[] interface {}
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...)
最佳答案
是的,有可能,只需将您的分片声明为[]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
不可转换。有关更多详细信息,请参见此问题和答案: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
}
关于go - 如何在Golang中将变量参数传递给Sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63933434/