Which generic helpers in slices and maps should a senior Go developer know, and what are their gotchas?
Question 139MediumGo 1.22 to 1.25
slices:Sort,SortFunc,BinarySearch,Index,Contains,Insert,Delete,DeleteFunc,Compact,Equal,Clone,Grow,Reverse,Max,Min. Iterator helpers (Go 1.23):All,Values,Collect,Sorted,Chunk.maps:Clone,Copy,Equal,DeleteFunc.Keys,ValuesandAllreturn iterators in Go 1.23.
m := map[string]int{"b": 2, "a": 1, "c": 3}
keys := slices.Sorted(maps.Keys(m)) // [a b c]; maps.Keys is iter.Seq[string]
s := []int{1, 2, 3, 4, 5}
t := s[:5]
s = slices.Delete(s, 1, 3) // [1 4 5]
fmt.Println(t) // Go 1.22+: [1 4 5 0 0] (tail zeroed)
i, found := slices.BinarySearch(keys, "b") // 1 true (slice must be sorted)
_, _ = i, found
u := slices.Compact([]int{1, 1, 2, 2, 1}) // [1 2 1]: only ADJACENT dups removed
fmt.Println(u)
Gotchas:
Delete,CompactandInsertmodify the backing array in place and return the new slice. Always use the returned value. Since 1.22,Delete,DeleteFunc,Compact,CompactFuncandReplacezero the obsolete tail, so other aliases see zeros.maps.Keysis not a slice. Wrap it withslices.Collectorslices.Sorted.Sortis not stable.- Go 1.22
slices.Concatpreallocates exactly, so it beats repeatedappend.
More on Generics
- Q137What is
golang.org/x/exp/constraints, how does it relate tocmp.Ordered, and how do you define your own numeric constraint? - Q138Explain the
cmppackage:Compare,Less,Or. How do you do a multi-key sort, and how is NaN handled? - Q140How do generics combine with Go 1.23 iterators (
iter.Seq)? Write lazyFilterandMapadapters and explain theyieldcontract. - Q141What is
iter.Pull, and when do you need it? Implement a genericZip. - Q142What are generic type aliases (Go 1.24), and how do they differ from generic type definitions?
- Q143Are generic types covariant? Can a
Box[Dog]be used as aBox[Animal], or aBox[int]converted to aBox[MyInt]?