我很懒,想把很多变量传递给Printf函数,有可能吗?(示例代码简化为3个参数,我需要10个以上的参数).
我收到以下消息:
不能在fmt.Printf的参数中使用v(type [] 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...)
Run Code Online (Sandbox Code Playgroud)
是的,有可能,只是声明你的切片是类型的,[]interface{}因为这是Printf()预期的.Printf()签名:
func Printf(format string, a ...interface{}) (n int, err error)
Run Code Online (Sandbox Code Playgroud)
所以这将有效:
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...)
Run Code Online (Sandbox Code Playgroud)
输出(Go Playground):
b c d
b c d
Run Code Online (Sandbox Code Playgroud)
[]interface{}并且[]string不可兑换.有关详细信息,请参阅此问题+答案:
如果您已经拥有[]string或使用了返回a的函数[]string,则必须手动将其转换为[]interface{},如下所示:
ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
is[i] = v
}
Run Code Online (Sandbox Code Playgroud)