Goworkinggo1.21

The slices and maps packages

Generic helpers that replace hand-rolled loops.

Go 1.21 added slices and maps β€” type-safe Sort, Contains, Index, Max/Min, Reverse, and maps.Keys, so common collection chores stop being for-loops.

Before Go 1.21 you wrote the same loops over and over: scan for a value, find its index, track a running maximum, reverse in place. The slices and maps packages in the standard library replace those with generic, type-safe helpers that work for any element type β€” no interface{}, no casts.

Sorting and searching

slices.Sort sorts any slice whose element type is ordered (numbers and strings) in place. slices.Contains reports membership, and slices.Index returns the position of the first match or -1 when absent. These three cover the bulk of everyday slice work.

Aggregates

slices.Max and slices.Min return the largest and smallest element of an ordered slice. They panic on an empty slice, so guard with len(s) > 0 when the input might be empty. For custom orderings (structs, reverse order) reach for the Func variants like slices.MaxFunc.

Reversing and map keys

slices.Reverse flips a slice in place. maps.Keys returns an iterator over a map's keys (Go 1.23+); collect it with slices.Collect, then slices.Sort to get deterministic order β€” map iteration order is otherwise random, so always sort before printing.

Try it 5 examples

slices.Sort sorts in place

Gointro
0ms
[1 2 3 5 8 9][apple fig pear]
Reference Β· output compiled offline, not runnable in-browser

One generic slices.Sort call sorts both the []int and the []string in place β€” ascending numeric order for the ints, lexicographic for the strings β€” with no comparator and no per-type code.