Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created July 19, 2019 08:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Integralist/256c445d1d56369632e43d49056b60cf to your computer and use it in GitHub Desktop.
[Golang Array and Slices] #go #golang #slice #slices #array #internal #pointers

I'll explain how 'slices' work as best I can, but it might be worth also reading this official go post on the subject: https://blog.golang.org/go-slices-usage-and-internals (it has some nice visual aids too).

A 'slice' is a data structure abstraction around the 'Array' composite data type.

An array is a fixed size and can't be resized once it is full. A slice also cannot dynamically grow larger at runtime, we must create a new slice, and this requires the use of the appropriate builtin functions.

The reason we have to use the builtin append function is because the slice data structure includes a pointer to an array in memory. When appending more data than can be fit into the underlying array, the slice will copy the original array data to a new array and will return a new slice with an updated pointer.

So if you tried to append the values "a", "b" and "c" to a slice s like so: append(s, "a", "b", "c") then this would return a new slice, but the original slice s would not be changed (i.e. it would still reference the original underlying/untouched array). Hence we overwrite s to ensure it is the updated slice with a potentially updated internal array pointer.

It's worth noting that if the underlying array has enough capacity, then although append will still return a new slice, the underlying array will be the same (as no new array needed to be allocated to hold the extra data). This can mean that updates happen to the underlying array when maybe you didn't intend them to.

There is also the ... syntax which is similar to rest/splat syntax in Python in that it unpacks the provided array/slice (e.g. append(s, anotherSlice...)).

There's also a gotcha which is worth being aware of, and is related to the fact that slices point to the same underlying array if the slice modifications didn't change the array's capacity: https://yourbasic.org/golang/gotcha-append/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment