Arrays and slices are ways to create “lists” of data in Go. The key difference between both is that arrays are of fixed size, while slices can grow and shrink in size.
Arrays
The type [n]T
is an array of n
values of type T
.
Is an empty array. Values can be accessed by: a[0] = 10
Arrays can be initialized when being declared
Arrays are fixed in size.
Slices
Slices aren’t fixed in size.
[]T
is a slice with elements of type T
Slices can be created like this:
- Slices don’t store any data
- Slices describe a section of an array that is created underlying
- Important: Other slices that share the same underlying array will see changes committed to a slice.
- TL;DR: Slices are like references to arrays, and arrays are always used under the hood
Array vs. slice literal
Slice length and capacity
- Length: Number of elements it contains
- Capacity: Number of elements in the underlying array
Functions len()
and cap()
can be used for this purpose.
Appending values to a slice
Multiple values can be appended once: append(aSlice, 1, 2, 3)
Range on slices
The first variable returned is always the index of the value. To “skip” this variable, use the following trick: for _, val := range a
Slices with make
- Used to create dynamically sized arrays
make
allocates a zeroed array and returns a slice that refers to this array- To append values to slices successfully, one doesn’t need to use
make
Why not always use slices in Go?
As slices offer more flexibility over arrays, one might come to the conclusion to use them always. While this is technically possible and might not come with downsides at first glance, there is something more to consider: Performance.
Slices are not as good when it comes to performance compared to arrays. One of the reasons is that arrays are predicable, as they are fixed in size. Therefore, the compiler can optimize memory usage etc.
Due to this reason, try to use arrays, when you don’t have a use case for a slice, e. g. when having a static list of data.
Next Chapter: Pointers