[The Go Blog] Go Slices: usage and internals
Go Slices: usage and internals
Introduction
Go’s slice type provides a convenient and efficient means of working with sequences of typed data. Slices are analogous to arrays in other languages, but have some unusual properties. This article will look at what slices are and how they are used.
Slices
Arrays have their place, but they’re a bit inflexible, so you don’t see them too often in Go code. Slices, though, are everywhere. They build on arrays to provide great power and convenience.
The type specification for a slice is []T
, where T
is the type of the elements of the slice. Unlike an array type, a slice type has no specified length.
A slice literal is declared just like an array literal, except you leave out the element count:
1 | letters := []string{"a", "b", "c", "d"} |
A slice can be created with the built-in function called make
, which has the signature,
1 | func make([]T, len, cap) []T |
where T
stands for the element type of the slice to be created. The make function takes a type, a length, and an optional capacity. When called, make allocates an array and returns a slice that refers to that array.
1 | var s []byte |
When the capacity argument is omitted, it defaults to the specified length. Here’s a more succinct version of the same code:
1 | s := make([]byte, 5) |
The length and capacity of a slice can be inspected using the built-in len and cap functions.
1 | len(s) == 5 |
The next two sections discuss the relationship between length and capacity.
The zero value of a slice is nil
. The len and cap functions will both return 0
for a nil slice.
A slice can also be formed by “slicing” an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression b[1:4]
creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2).
1 | b := []byte{'g', 'o', 'l', 'a', 'n', 'g'} |
The start and end indices of a slice expression are optional; they default to zero and the slice’s length respectively:
1 | // b[:2] == []byte{'g', 'o'} |
This is also the syntax to create a slice given an array:
1 | x := [3]string{"Лайка", "Белка", "Стрелка"} |
Slice internals
A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
Our variable s
, created earlier by make([]byte, 5)
, is structured like this:
The length is the number of elements referred to by the slice. The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer). The distinction between length and capacity will be made clear as we walk through the next few examples.
As we slice s, observe the changes in the slice data structure and their relation to the underlying array:
1 | s = s[2:4] |
Slicing does not copy the slice’s data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice:
1 | d := []byte{'r', 'o', 'a', 'd'} |
Earlier we sliced s to a length shorter than its capacity. We can grow s to its capacity by slicing it again:
1 | s = s[:cap(s)] |
A slice cannot be grown beyond its capacity. Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array. Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.
Growing slices (the copy and append functions)
To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. This technique is how dynamic array implementations from other languages work behind the scenes.
The common operation is made easier by the built-in copy
function. As the name suggests, copy copies data from a source slice to a destination slice. It returns the number of elements copied.
1 | func copy(dst, src []T) int |
The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements). In addition, copy can handle source and destination slices that share the same underlying array, handling overlapping slices correctly.
Using copy, we can simplify the code snippet above:
1 | t := make([]byte, len(s), (cap(s)+1)*2) |
A common operation is to append data to the end of a slice. Go provides a built-in append
function that’s good for most purposes; it has the signature
1 | func append(s []T, x ...T) []T |
The append function appends the elements x to the end of the slice s, and grows the slice if a greater capacity is needed.
1 | a := make([]int, 1) |
To append one slice to another, use ...
to expand the second argument to a list of arguments.
1 | a := []string{"John", "Paul"} |
Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:
1 | // Filter returns a new slice holding only |
A possible “gotcha”
As mentioned earlier, re-slicing a slice doesn’t make a copy of the underlying array. The full array will be kept in memory until it is no longer referenced. Occasionally this can cause the program to hold all the data in memory when only a small piece of it is needed.
For example, this FindDigits function loads a file into memory and searches it for the first group of consecutive numeric digits, returning them as a new slice.
1 | var digitRegexp = regexp.MustCompile("[0-9]+") |
This code behaves as advertised, but the returned []byte points into an array containing the entire file. Since the slice references the original array, as long as the slice is kept around the garbage collector can’t release the array; the few useful bytes of the file keep the entire contents in memory.
To fix this problem one can copy the interesting data to a new slice before returning it:
1 | func CopyDigits(filename string) []byte { |
A more concise version of this function could be constructed by using append. This is left as an exercise for the reader.
Further Reading
Effective Go contains an in-depth treatment of slices - https://golang.org/doc/effective_go.html#slices and arrays - https://golang.org/doc/effective_go.html#arrays, and the Go language specification - https://golang.org/doc/go_spec.html defines slices - https://golang.org/doc/go_spec.html#Slice_types and their associated helper functions - https://golang.org/doc/go_spec.html#Appending_and_copying_slices.
References
[1] Go Slices: usage and internals - The Go Blog - https://blog.golang.org/slices-intro
[2] slices - https://golang.org/doc/effective_go.html#slices
[3] language specification - https://golang.org/doc/go_spec.html
[4] slices - https://golang.org/doc/go_spec.html#Slice_types