Using a pointer to array

The Google Go docs state the following about passing arrays – they say you usually want to pass a slice (instead of a pointer?):

Updated:

As indicated by @Chickencha’s comment, array slices are references which is why they are efficient for passing. Therefore likely you will want to use the slice mechanism instead of “raw” pointers.

From Google Effective Go doc http://golang.org/doc/effective_go.html#slices

Slices are reference types,


Original

It’s under the heading

An Interlude about Types

[…snip…] When passing an array
to a function, you almost always want
to declare the formal parameter to be
a slice. When you call the function,
take the address of the array and Go
will create (efficiently) a slice
reference and pass that.

Editor’s note: This is no longer the case

Using slices one can write this function (from sum.go):

09    func sum(a []int) int {   // returns an int
10        s := 0
11        for i := 0; i < len(a); i++ {
12            s += a[i]
13        }
14        return s
15    }

and invoke it like this:

19        s := sum(&[3]int{1,2,3})  // a slice of the array is passed to sum    

Maybe pass the whole array as a slice instead. Google indicates Go deals efficiently with slices. This is an alternate answer to the question but maybe it’s a better way.

Leave a Comment