Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 147 ยท Collections

The slices and maps Packages

Master Go's slices, maps and cmp packages - Sort, SortFunc, BinarySearch, Contains, Index, Compact, Insert, Delete, Clone, Collect, Sorted, maps.Keys, maps.DeleteFunc, cmp.Compare and cmp.Or.

Before Go 1.21, every project had its own little helpers: contains, indexOf, reverse, keys. Once generics arrived, the standard library finally shipped the real thing. The slices package works on any slice, the maps package works on any map, and cmp provides the comparison helpers they share. Together they replace hundreds of hand-written loops.

All three packages are generic, so one function handles []int, []string or a slice of your own structs. The functions are small, fast and well tested, so reach for them first. This lesson tours the ones you'll use daily and shows which Go version introduced the newer ones.

Searching: Contains, Index and friends

The simplest helpers answer "is it in there?" and "where?". They compare with ==, so the element type must be comparable. Variants ending in Func take a predicate for everything else:

Go Contains, Index and their Func variants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

slices.Compare returns -1, 0 or +1, comparing element by element like a dictionary compares words. You'll see this -1/0/+1 convention throughout this lesson.

Sorting and searching a sorted slice

slices.Sort sorts any slice of ordered elements (numbers and strings) in place, ascending. For anything else you pass a comparison function to slices.SortFunc. It must return a negative number, zero or a positive number, exactly the contract of strings.Compare. The cmp.Compare function gives you that for any ordered type:

Go Sort, SortFunc and BinarySearch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The next lesson, Sorting, goes deep on multi-key sorts and stability. For now, remember that slices.Sort is the one-liner for numbers and strings.

Min, max and reordering

slices.Min and slices.Max return the smallest and largest element and panic on an empty slice. Check len first, or use the Func forms for custom types. Reverse flips a slice in place:

Go Min, Max and Reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last line panics with the message slices.Max: empty list, which the deferred function catches with recover (see panic and recover).

Editing: Insert, Delete, Compact, Clone

These replace the tricky append idioms from Slices. All of them return a new slice header and, like append, you must use the result:

Go Insert, Delete, Compact and Clone

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Delete and DeleteFunc shift the tail down and then zero the vacated slots, which matters when elements are pointers (since Go 1.22), as How Slices Work explained. The old slice variable still sees the shifted data, so don't keep using it after the call.

Building and splitting: Concat, Repeat, Chunk

A few newer helpers construct slices: slices.Concat (Go 1.22) joins any number of slices into a new one, slices.Repeat (Go 1.23) repeats a slice, and slices.Chunk (Go 1.23) splits a slice into pieces of at most n elements. Chunk returns an iterator, which we'll meet below:

Go Concat, Repeat and Chunk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Chunk is perfect for batching database inserts or API calls. The batches are sub-slices of the original, so they share its memory, and Chunk panics if n < 1.

Iterators: All, Values, Backward, Collect, Sorted

Go 1.23 added iterators, functions you can loop over with for range (the full story is in Iterators). The slices and maps packages use them to connect slices and maps to each other:

Function What it does
slices.All(s) iterator over index, value pairs
slices.Values(s) iterator over values only
slices.Backward(s) index, value pairs from last to first
slices.Collect(seq) gather an iterator into a new slice
slices.Sorted(seq) collect and sort in one step
slices.SortedFunc(seq, cmp) collect and sort with a custom comparison
maps.Keys(m) / maps.Values(m) iterator over keys / values (random order)
maps.All(m) iterator over key, value pairs
maps.Collect(seq2) build a map from key, value pairs
maps.Insert(m, seq2) add pairs to an existing map
Go Iterators connecting slices and maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

slices.Sorted(maps.Keys(m)) is the idiom you'll write most often. It replaces the four-line "make a slice, append keys, sort" loop from the Maps lesson.

The maps package

The maps package is smaller because maps have fewer operations. Clone copies a map, Equal compares two, Copy merges one into another (the source wins on clashes), and DeleteFunc removes every entry the predicate accepts:

Go Clone, Equal, Copy and DeleteFunc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

maps.Clone is shallow: if the values are slices, pointers or other maps, the clone shares them. Cloning a nil map returns nil.

The cmp package

cmp.Compare(a, b) returns -1, 0 or +1 for any ordered type (numbers and strings), and handles floating-point NaN consistently (NaN sorts before every other number). cmp.Less is the boolean version. Its best trick is cmp.Or, which returns the first argument that is not the zero value, so you can chain comparisons for multi-key sorting:

Go cmp.Compare and cmp.Or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

cmp.Or was added in Go 1.22. Because cmp.Compare returns 0 when two keys tie, Or moves on to the next key. That is why a multi-key comparison collapses into one readable expression.

When you reach for a hand-written loop over a slice or map, check slices and maps first. If the function exists, it has already been tuned and tested, and your intent is clearer to the reader.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call returns the position of "b" in s := []string{"a", "b"}?

    slices.Index returns the first index of the value, or -1. Contains returns only a bool.
  2. 2. What does slices.Compact([]int{1, 1, 2, 1}) return?

    Compact removes only consecutive duplicates. The trailing 1 is not next to another 1, so it stays. Sort first to remove all duplicates.
  3. 3. Which expression gives the keys of a map in sorted order?

    maps.Keys returns an iterator and slices.Sorted collects and sorts it. Map keys alone come back in random order.
  4. 4. What does slices.Max([]int{}) do?

    Min and Max panic on an empty slice because there is no sensible result. Check len(s) first.
  5. 5. What does cmp.Or(0, 0, 7, 9) return?

    cmp.Or returns the first argument that is not the zero value, which is 7.

Summary

  • slices (Go 1.21), maps (Go 1.21) and cmp (Go 1.21) are generic helpers for every slice and map.
  • Search with Contains, Index, IndexFunc, BinarySearch (sorted input only) and compare with Equal and Compare.
  • Sort with slices.Sort for ordered types and slices.SortFunc with cmp.Compare for everything else.
  • Edit with Insert, Delete, DeleteFunc, Compact, Replace, Clone, Concat (1.22) and Repeat (1.23). Always use the returned slice.
  • slices.Chunk, All, Values, Backward, Collect and Sorted (1.23) connect slices to iterators.
  • maps.Keys, Values, Clone, Copy, Equal and DeleteFunc cover the usual map chores. Map iterator order is random, so sort before printing.
  • cmp.Or (1.22) chains comparisons for multi-key sorts and picks defaults.

Next: Sorting goes deeper into sort order, stability, multi-key sorting and the older sort package.