Passing an array as an argument in golang
arguments, arrays, go
Solution
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) {
...
}
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.
You can find a more details on arrays and slices, and common pitfalls when using them here
Problem
Why does this not work? ``` 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) } } ``` Error: ``` .\structtest.go:15: cannot use a (type [3]name) as type []name in function argument ```