这个问题在这里已经有了答案:
Type converting slices of interfaces
(8 个回答)
2年前关闭。
当参数为 ... 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...)
您可以通过
string
在哪里 interface{}
是必需的,但您不能通过 []string
在哪里 []interface{}
必需的。编译器转换 string
值为 interface{}
值,但这不适用于数组,您必须自己进行翻译。
关于go - 我如何将 []string 作为 ...interface{} 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59674177/