问题内容
当参数为 ...strings 时,我知道如何传递它
但是这个例子有点不同:
func main() {
args := []string{"hello", "world"}
fmt.Println(args...)
}
https://play.golang.org/p/7eldqqvdpvr
上面的代码抛出错误 cannot use args (type [] string) as type [] interface {} in argument to fmt.println
实现这一目标的最惯用的方法是什么?
解决方案
这可以通过以下两种方式之一完成:
args := []interface{}{"hello", "world"}
fmt.println(args...)
或者:
args:=[]string{"hello", "world"}
iargs:=make([]interface{},0)
for _,x:=range args {
iargs=append(iargs, x)
}
fmt.Println(iargs...)
您可以在需要 interface{} 的情况下传递 string,但在需要 []interface{} 的情况下不能传递 []string。编译器会将 string 值转换为 interface{} 值,但数组不会这样做,您必须自己进行转换。
好了,本文到此结束,带大家了解了《我如何将字符串作为 …interface{} 参数传递》,希望本文对你有所帮助!关注公众号,给大家分享更多Golang知识!