在golang中将数组作为参数传递 [英] Passing an array as an argument in golang
问题描述
为什么这不起作用?
package main
import "fmt"
type name struct {
X string
}
func main() {
var a [3]name
a[0] = name{"Abbed"}
a[1] = name{"Ahmad"}
a[2] = name{"Ghassan"}
nameReader(a)
}
func nameReader(array []name) {
for i := 0; i < len(array); i++ {
fmt.Println(array[i].X)
}
}
错误:
.\structtest.go:15: cannot use a (type [3]name) as type []name in function argument
推荐答案
您已将函数定义为接受切片作为参数,同时尝试在对该函数的调用中传递数组.有两种方法可以解决这个问题:
You have defined your function to accept a slice as an argument, while you're trying to pass an array in the call to that function. There are two ways you could address this:
在调用函数时从数组中创建一个切片.像这样改变电话应该足够了:
Create a slice out of the array when calling the function. Changing the call like this should be enough:
nameReader(a[:])
更改函数签名以获取数组而不是切片.例如:
Alter the function signature to take an array instead of a slice. For instance:
func nameReader(array [3]name) {
...
}
这个解决方案的缺点是该函数现在只能接受长度为 3 的数组,并且在调用它时会复制该数组.
Downsides of this solution are that the function can now only accept an array of length 3, and a copy of the array will be made when calling it.
您可以在此处找到有关数组和切片的更多详细信息以及使用它们时的常见陷阱:http://openmymind.net/The-Minimum-You-Need-To-Know-About-Arrays-And-Slices-In-Go/一个>
You can find a more details on arrays and slices, and common pitfalls when using them here: http://openmymind.net/The-Minimum-You-Need-To-Know-About-Arrays-And-Slices-In-Go/
这篇关于在golang中将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!