Which slices and maps package functions do you use daily, and how do they work with iterators (Go 1.23)?
Question 54MediumGo 1.22 to 1.25
Go 1.21 added slices and maps to the standard library. Go 1.23 added iterator-returning functions based on iter.Seq / iter.Seq2 and range-over-func.
s := []int{3, 1, 4, 1, 5, 9, 2, 6}
slices.Sort(s) // pdqsort, not stable; use SortStableFunc for stability
i, found := slices.BinarySearch(s, 5) // requires sorted input
s = slices.Compact(s) // removes *consecutive* duplicates
fmt.Println(i, found, s, slices.Contains(s, 9), slices.Index(s, 4))
slices.Reverse(s) // in place
fmt.Println(slices.Max(s), s)
// Sorting structs
type User struct{ Name string; Age int }
users := []User{{"b", 30}, {"a", 30}, {"c", 25}}
slices.SortFunc(users, func(a, b User) int {
return cmp.Or(cmp.Compare(a.Age, b.Age), strings.Compare(a.Name, b.Name))
})
// Iterators (Go 1.23)
m := map[string]int{"z": 1, "a": 2, "m": 3}
keys := slices.Sorted(maps.Keys(m)) // deterministic key order
for k, v := range maps.All(m) { _, _ = k, v }
for chunk := range slices.Chunk(s, 3) { fmt.Println(chunk) }
evens := slices.Collect(func(yield func(int) bool) {
for _, v := range s {
if v%2 == 0 && !yield(v) {
return
}
}
})
m2 := maps.Collect(slices.All([]string{"x", "y"})) // map[int]string{0:"x",1:"y"}
_, _ = evens, m2
Gotchas:
maps.Keysreturns an iterator, not a slice. That changed fromx/exp/maps.slices.Compactremoves only adjacent duplicates, so sort first.slices.Insert,DeleteandGrowreturn a new slice that you must reassign.
More on Arrays, Slices, Maps & Strings
- Q52How do you correctly allocate a 2D slice, and what are the performance trade-offs?
- Q53Why do the slices package functions use the constraint [S ~[]E, E any] instead of just []E?
- Q55Describe how Go maps were implemented before Go 1.24 (buckets, tophash, load factor, growth).
- Q56What changed in Go 1.24 with Swiss Tables? Why are they faster?
- Q57Why is map iteration order random, and how do you iterate deterministically?
- Q58Is it safe to add or delete map entries while ranging over the map?