arrays - 为什么在 Go 中调用可变参数函数时不能_直接_使用数组?

标签 arrays go slice variadic-functions

给定一个(可变参数)函数的原因是什么

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/

相关文章:

java - "Removing"数组中的偶数并将奇数移动到前面

javascript - 如何找到两个 JavaScript 对象数组之间的差异?

arrays - 解析显式数组

go - go lang 中类似 slice 移位的函数

javascript - 如何将数组中的每个元素与不同数组中的其他元素合并?

go - 如何在 Golang 中对多个变量应用单独的 Mutex?

调用 Go RPC TCP 服务时 Ruby Socket 客户端挂起

go - 如何将 zap 记录器与 go-kit 一起使用?

arrays - 使用 each_with_slice 拆分数组但在结果数组中保留特定值(一个衬里)

javascript - 从内部函数中的父作用域访问数组元素