Slices in Go
Slices are the primary way to work with sequences of data in Go. Unlike arrays, slices are dynamically sized and act as a view into an underlying array.
Syntax
A slice literal looks like an array literal but without the size.
mySlice := []int{1, 2, 3}
Slicing an Array
You can create a slice by “slicing” an existing array or slice using the [low:high] syntax.
primes := [6]int{2, 3, 5, 7, 11, 13}
mySlice := primes[1:4] // {3, 5, 7}
- low: Inclusive (defaults to 0).
- high: Exclusive (defaults to length).
Characteristics
- References: Slices hold references to an underlying array. Modifying a slice element changes the underlying array.
- Nil Slices: The zero value of a slice is
nil. A nil slice has no underlying array.