During my initial steps learning the Go language, familiar with pointers, I ran into some difficulties grasping why do “reference types” (as the Go language spec as well as other Go resources, actually call them) behave the way they do, and how do they really look like under the hood, as the name “reference types” confuses a bit.
Searching through the web, I came across this ‘golang-nuts’ forum thread which cleared it all up for me and hopefully I’ll be able to summarize the good parts in this post.
Also note, that although this post focuses on Slices, Maps and Channels work the same way.
- You may think of slices as a struct with the following 3 fields:
- array (holds a pointer to an array)
- len (holds the pointed array’s length)
- cap (holds the pointed array’s capacity)
In Go, arguments are always passed to functions by value (you can argue with that by saying that you can always pass a pointer to the real instance, but even then:
you’re actually passing a copy of the original pointer).
Slices are no different: when passing a slice as an argument (by value), you’re actually passing a copy of the struct I described above, to the function.
The pointer in that ‘struct copy’ refers to the same array as the original struct, meaning that when you’re altering the slice’s elements, you’re actually altering the pointed array’s elements and as a result, the changes are reflected in the original slice. This part is pretty straightforward.
Now for the more interesting part:
When you perform operations that alter the struct’s fields (as opposed to altering the slice’s elements), like expanding the slice using
append(slice) (resulting a greater
len and sometimes a greater
capacity) they will not be reflected in the original struct,
the reason is obvious: all you’re doing is altering a copy.
Hopefully, the following example will better reflect the above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53