Go: Slices explained
A slice is a view of an underlying array. You can use s[i]
to view and modify an element of a slice s
. Modifications will affect the underlying array as well.
You may think of a slice as a descriptor of an array segment:
- passing a slice as argument to a method does not cause the data to be copied (as with arrays),
- and a slice can grow and shrink within the bounds of the underlying array.
Create
The type of a slice is []T
. Here's a simple way to declare and initialize a slice:
s := []string{"foo", "bar", "baz", "qux"}
Here's how to use the make
function to create and initialize a slice with five zeroes:
s := make([]int, 5)
You can also create a slice backed by an existing array.
Length and capacity
The length and capacity can be retrieved using the built-in functions len
and cap
.
The make
function optionally takes a capacity as a third argument. make([]int, 10, 100)
for example, is the same as new([100]int)[:10]
.
Reslice and extend
You can slice a slice:
The indices in the last line are relative to the slice itself, not to the backing array. The end index is not bound by the slice's length, but by it's the capacity, which means we can extend the slices length:
Trying to extend beyond the capacity will cause a panic. You can not use a negative start index.
Append
There's a built-in function called append
which appends elements to a slice. It will automatically allocate a larger backing array if the capacity is exceeded.
Zero value
The default value of a slice is nil
. The functions len
, cap
and append
all regard nil
as an empty slice with 0 capacity.