Go

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, Values and All return 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, Compact and Insert modify the backing array in place and return the new slice. Always use the returned value. Since 1.22, Delete, DeleteFunc, Compact, CompactFunc and Replace zero the obsolete tail, so other aliases see zeros.
  • maps.Keys is not a slice. Wrap it with slices.Collect or slices.Sorted.
  • Sort is not stable.
  • Go 1.22 slices.Concat preallocates exactly, so it beats repeated append.

More on Generics

All 36 Generics questions