Slices & Arrays in 2 mins
We had another mentoring session on Teams. I think/hope I conveyed the information more clearly this week, but provided a summary just in case :D
Another week and another 20 minutes helping my colleagues make progress with #golang.
This week we covered Slices & Arrays and this is how I summarised the session.
Hope it helps & please share with your Gopher friends!
Go has both arrays and slices. Slices - in Go - are a convenience “wrapper” around arrays.
Why do we need slices? Why are they helpful?
Arrays are defined with a size and capacity using the make command - like you might use to create a map.
Arrays can't be resized, their size and capacity is a part of their type.
If you need more space in an array you need to copy the array to a *new* array with more capacity.
Slices hide all this away from us. They also provide a convenient `append` function for adding elements to slices without having to specify the index or worry about size & capacity.
Slices are a reference type, which for a slice means they are a reference to a backing array.
When adding to a slice, Go will populate the backing array for us.
Go will also handle copying the backing array to a new larger array with more capacity as and when needed.
Since slices are a reference type we don't need to explicitly pass them about by reference (memory address) to use the original - the backing array is the original!
Most of the time, slices are ideal and convenient, we use them as if they were actually arrays.
So when might we prefer to use arrays?
If we know the amount of the data we wish to store ahead of time.
If we want to ensure we make efficient use of memory.
I’m not sure of the ruleset that governs how much additional capacity Go will create every time it copies the backing array of a slice, to a new array in order to provide additional capacity, but, looking at this example I wrote up, it's circa 25% more capacity each time.
Slice resizing example:- https://play.golang.org/p/N_LCL5K05Yl
If you run that, can you see how this can lead to situations where the backing array has been resized by an additional 25%, only to use a single additional element in the slice?
In large datasets this might be a less than optimal use of memory, so that's probably the only time I might consider using arrays over slices. For most use-cases slices are perfect.