Beginner Fundamentals
Slices
A slice is a flexible, growable view over a sequence of elements. Slices are the most common way to work with lists in Go.
Creating a slice
fruits := []string{"apple", "pear"}
fmt.Println(fruits) // [apple pear]
Note there is no size inside the brackets, unlike an array.
append
append adds elements and returns a new slice, which you assign back.
fruits = append(fruits, "plum")
fmt.Println(fruits) // [apple pear plum]
len and cap
len is the number of elements; cap is how many it can hold before growing.
nums := make([]int, 2, 5)
fmt.Println(len(nums)) // 2
fmt.Println(cap(nums)) // 5
Slicing
You can take a sub-slice with [low:high]. The high index is excluded.
letters := []string{"a", "b", "c", "d", "e"}
middle := letters[1:4]
fmt.Println(middle) // [b c d]
Omitting an index uses the start or end:
fmt.Println(letters[:2]) // [a b]
fmt.Println(letters[3:]) // [d e]