给定一个(可变参数)函数的原因是什么
func varargs(n ...int) {}
可以这样称呼
varargs(1, 2, 3, 4) // Fixed number of arguments
但不是数组:
a := [4]int{1, 2, 3, 4} // Fixed number of elements
varargs(a...) // Error: cannot use (type [4]int) as type []int in argument
我明白为什么
var s []int = a
不会工作:它可以防止意外误用,需要手动 slice :
s := a[:]
但为什么此限制会扩展到对可变参数函数的调用?
奖励问题:
反过来,为什么会调用
func fourargs(w, x, y, z int) {}
4 元素数组
fourargs(a...) // Error: not enough arguments in call have ([4]int...)
// want (int, int, int, int)
也被禁止了?
它可以在编译时进行类型检查。
最佳答案
Spec: Passing arguments to ... parameters:
If the final argument is assignable to a slice type
[]T
, it may be passed unchanged as the value for a...T
parameter if the argument is followed by...
. In this case no new slice is created.
因此,当您有一个 slice 并将其作为可变参数的值传递时,不会创建新 slice ,它只是被分配。
如果你有一个不同类型的数组,它不能分配给 slice 类型。因此这是不允许的。
您必须首先对数组进行 slice ,您可以在没有中间变量的情况下执行此操作:
a := [4]int{1, 2, 3, 4}
varargs(a[:]...)
是的,您可以说这种自动 slice 可以自动/在内部发生。为什么不允许这样做是基于意见的(并且属于 Go 的作者)。基本上,在 Go 中数组是次要的。 slice 是要走的路。你应该首先有一个 slice ,你可以通过并且你没有问题。查看相关问题:Why have arrays in Go?和 Slicing a slice pointer passed as argument .
关于arrays - 为什么在 Go 中调用可变参数函数时不能_直接_使用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55651147/