go - 我如何将 []string 作为 ...interface{} 参数传递

标签 go slice variadic

这个问题在这里已经有了答案:





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/

相关文章:

python - 有条件地合并文本文件中的行

python - 值错误 : setting an array element with a sequence

c++ - 无法删除不需要的重载

go - 有条件的导入golang

for-loop - Go中for循环内的错误处理可能会导致下一次迭代

python - pandas:切片 Multiindex 有很多索引

c++ - 在 C++11 中打印编译时整数序列

coq - Ltac : optional arguments tactic

go - 如何延迟函数返回的匿名函数

go - Go 方法中的默认值