Go

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.Keys returns an iterator, not a slice. That changed from x/exp/maps.
  • slices.Compact removes only adjacent duplicates, so sort first.
  • slices.Insert, Delete and Grow return a new slice that you must reassign.

More on Arrays, Slices, Maps & Strings

All 37 Arrays, Slices, Maps & Strings questions