我很懒,想将许多变量传递给Printf函数,这可能吗? (示例代码简化为3个参数,我需要10个以上的参数.)
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).
我收到以下消息:
在fmt.Printf的参数中不能将v(类型[]字符串)用作类型[] interface {}
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...)
推荐答案
是的,有可能,只需声明您的切片为[]interface{}类型,因为这就是 Printf() 期望. Printf()签名:
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)所以这将起作用:
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...)输出(进入游乐场):
b c d b c d[]interface{}和[]string不可转换.有关更多详细信息,请参阅此问题和答案:
[]interface{} and []string are not convertible. See this question+answers for more details:
在接口中进行类型转换的切片
Type converting slices of interfaces in go
如果您已经有[]string或使用了返回[]string的函数,则必须手动将其转换为[]interface{},如下所示:
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 }更多推荐
如何在Golang中将变量参数传递给Sprintf
发布评论