Arrays, Slices & Maps
How slices share memory, append and capacity, the slices package, and maps with comma-ok.
Slices are Go's everyday list type: a view onto an underlying array with a length and a capacity. Understanding that a slice shares memory with its array explains most slice surprises. Maps are built-in hash tables.
Slices and maps
arr[1:3] is a slice of elements 1 and 2; writing s[0] = 99 changes arr too, because they share memory.
append adds elements, allocating a bigger array when the capacity runs out.
make([]int, 0, 8) preallocates capacity; copy copies elements between slices.
slices.Sort, slices.Contains and slices.Max come from the standard slices package (Go 1.21+).
name, ok := owners["can"]: ok reports whether the key existed.
Map iteration order is randomized, so keys are sorted with slices.Sorted(maps.Keys(...)) before printing.
append(readings, 36.8) // result discarded readings = append(readings, 36.8) append may return a new slice backed by a new array; always assign the result.
var m map[string]int m["x"] = 1 // panic: assignment to entry in nil map m:= map[string]int{} // or make(map[string]int) A nil map can be read but not written.
What is the difference between len and cap of a slice?
len is the number of elements in the slice; cap is how many elements fit in the underlying array from the slice's start before append must reallocate.