So we’ve learned about the fixed-length, and therefore somewaht limited, array types. Let’s now look at the more flexible cousin, the slice
.
Slice types
A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The number of elements is called the length of the slice and is never negative. The value of an uninitialized slice is
nil
.SliceType = "[" "]" ElementType .
Okay, so what does that all mean?
It basically means that a slice can be thought of as a view into an underlying array.
Let me illustrate with an example:
// Initialize a as an array of 10 integers
var a = [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
// Initialize s as a slice "view" of a, of indexes 0, 1, and 2
var s = a[0:3]
fmt.Println(a, s) // Prints: [0 1 2 3 4 5 6 7 8 9] [0 1 2]
See this code in the playground
Quotes from The Go Programming Language Specification, Version of January 19, 2023