Slices, arrays and maps

Grow a slice with append, look up a map with the comma-ok form, and sort with slices and sort.

Runs in Zerethon IDE · Go 1.27 Official Go documentation ↗
main.go
package main

import (
	"fmt"
	"maps"
	"slices"
	"sort"
)

func main() {
	scores := []int{70, 95, 82}
	scores = append(scores, 60)
	sorted := slices.Clone(scores)
	slices.Sort(sorted)
	fmt.Println(sorted, scores[0], scores[len(scores)-1], len(scores))
	fmt.Println(sorted[1:3], slices.Contains(scores, 95))

	ages := map[string]int{"ada": 36, "alan": 41}
	ages["grace"] = 85
	age, ok := ages["linus"]
	fmt.Println(age, ok)
	for _, name := range slices.Sorted(maps.Keys(ages)) {
		fmt.Println(name, ages[name])
	}

	type person struct {
		name string
		age  int
	}
	people := []person{{"bob", 25}, {"amy", 31}}
	sort.Slice(people, func(i, j int) bool { return people[i].age > people[j].age })
	fmt.Println(people)
}

Output

[60 70 82 95] 70 60 4
[70 82] true
0 false
ada 36
alan 41
grace 85
[{amy 31} {bob 25}]
  • A slice ([]int) grows; an array ([3]int) has a fixed length that is part of its type. You almost always want a slice.
  • append may return a new slice — always assign the result: s = append(s, x).
  • s[a:b] shares memory with s; changing one changes the other. slices.Clone makes a copy.
  • A missing map key gives the zero value. v, ok := m[k] tells you whether it was there.
  • Map iteration order is random on purpose. Sort the keys when the order matters.

Watch out: Writing to a map declared with var m map[string]int panics (assignment to entry in nil map). Create it first: m := map[string]int{} or make(map[string]int).