IntermediateLesson 6 of 15
Arrays, Slices & Maps – Go
The core collection types and their pitfalls.
An array has a fixed length ([3]int), a slice ([]int) grows dynamically and is the default type for lists. A slice is a view onto an array in memory: it consists of a pointer, a length (len) and a capacity (cap). append adds elements and returns the (possibly new) slice – you must always assign the result.
package main
import (
"fmt"
"sort"
)
func main() {
arr := [3]int{1, 2, 3} // array: fixed length
s := []int{3, 1, 2} // slice: dynamic
s = append(s, 5)
sort.Ints(s)
fmt.Println(arr, s, len(s)) // [1 2 3] [1 2 3 5] 4
a := []int{10, 20, 30, 40, 50}
b := a[1:3] // [20 30] – shares memory with a
b[0] = 99
fmt.Println(a, b, len(b), cap(b)) // [10 99 30 40 50] [99 30] 2 4
c := make([]int, 3) // [0 0 0]
n := copy(c, a)
fmt.Println(c, n) // [10 99 30] 3
}A map associates keys with values. When reading, the "comma ok" expression additionally tells you whether the key exists. Missing keys yield the zero value – handy for counting.
package main
import (
"fmt"
"strings"
)
func main() {
person := map[string]string{"name": "Ada", "stadt": "London"}
person["alter"] = "36"
if email, ok := person["email"]; !ok {
fmt.Println("no email")
} else {
fmt.Println(email)
}
delete(person, "stadt")
fmt.Println(len(person)) // 2
zaehler := make(map[string]int)
for _, w := range strings.Fields("a b a c b a") {
zaehler[w]++
}
fmt.Println(zaehler) // map[a:3 b:2 c:1]
}The slices package (since Go 1.21) provides helper functions such as Sort, Contains, Index, Max, Reverse; maps and slices.Sorted help with keys:
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
zahlen := []int{5, 2, 8}
slices.Sort(zahlen)
fmt.Println(zahlen, slices.Contains(zahlen, 8), slices.Max(zahlen)) // [2 5 8] true 8
m := map[string]int{"b": 2, "a": 1, "c": 3}
schluessel := slices.Sorted(maps.Keys(m)) // Go 1.23+
fmt.Println(schluessel) // [a b c]
}WarningWriting to a
nil map causes a panic (var m map[string]int; m["a"] = 1) – create maps with make or a literal. Slices that share memory affect each other; use slices.Clone or copy when you need an independent copy.TipA
nil slice is a valid empty slice: var s []int; s = append(s, 1) works. With make([]T, 0, n) you reserve capacity in advance and avoid copying.