The slices Package

The standard library's slices package provides generic functions that work on slices of any type: searching, comparing, sorting, inserting, removing duplicates, finding the minimum and maximum, and more. Before it existed, Go programmers wrote these loops by hand over and over. This lesson tours the most useful functions.

Searching

GO
package main

import (
	"fmt"
	"slices"
	"strings"
)

func main() {
	langs := []string{"Go", "Rust", "Zig", "Python"}

	fmt.Println(slices.Contains(langs, "Zig"), slices.Index(langs, "Rust"), slices.Index(langs, "C"))

	long := func(s string) bool { return len(s) > 3 }
	fmt.Println(slices.ContainsFunc(langs, long), slices.IndexFunc(langs, long))

	i := slices.IndexFunc(langs, func(s string) bool { return strings.HasPrefix(s, "Z") })
	fmt.Println(langs[i])
}
Output
true 1 -1
true 1
Zig

The …Func versions take a function that decides whether an element matches, so you can search on any condition.

Comparing

Slices can't be compared with ==. Use slices.Equal for element-by-element equality and slices.Compare for ordering:

GO
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{1, 2, 3}
	b := []int{1, 2, 3}
	c := []int{1, 2, 4}
	fmt.Println(slices.Equal(a, b), slices.Equal(a, c))
	fmt.Println(slices.Compare(a, c), slices.Compare(c, a), slices.Compare(a, b))
}
Output
true false
-1 1 0

Min, max and sorting

GO
package main

import (
	"fmt"
	"slices"
)

func main() {
	temps := []float64{21.5, 18.0, 25.3, 19.8}
	fmt.Println(slices.Min(temps), slices.Max(temps))

	slices.Sort(temps) // sorts in place
	fmt.Println(temps, slices.IsSorted(temps))

	i, found := slices.BinarySearch(temps, 21.5) // fast search in a sorted slice
	fmt.Println(i, found)

	slices.Reverse(temps)
	fmt.Println(temps)
}
Output
18 25.3
[18 19.8 21.5 25.3] true
2 true
[25.3 21.5 19.8 18]

Min and Max panic on an empty slice, so check the length first when the data could be empty. Lesson 29 covers custom sort orders.

Inserting, deleting and replacing

GO
package main

import (
	"fmt"
	"slices"
)

func main() {
	s := []string{"a", "b", "c", "d", "e"}

	s = slices.Insert(s, 2, "X", "Y")
	fmt.Println(s)

	s = slices.Delete(s, 0, 2) // remove indexes 0 and 1
	fmt.Println(s)

	s = slices.DeleteFunc(s, func(v string) bool { return v == "d" })
	fmt.Println(s)

	s = slices.Replace(s, 0, 2, "Z") // replace indexes 0..1 with "Z"
	fmt.Println(s)
}
Output
[a b X Y c d e]
[X Y c d e]
[X Y c e]
[Z c e]

Like append, these return the updated slice, which you assign back. DeleteFunc is the easiest way to filter a slice in place.

Removing duplicates

slices.Compact replaces runs of equal neighbours with a single element. Sort first to remove all duplicates:

GO
package main

import (
	"fmt"
	"slices"
)

func main() {
	tags := []string{"go", "web", "go", "api", "web", "go"}
	slices.Sort(tags)
	tags = slices.Compact(tags)
	fmt.Println(tags)
}
Output
[api go web]

Building slices

GO
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{1, 2}
	b := []int{3}
	c := []int{4, 5}
	fmt.Println(slices.Concat(a, b, c))
	fmt.Println(slices.Repeat([]string{"ab"}, 3))

	for chunk := range slices.Chunk([]int{1, 2, 3, 4, 5, 6, 7}, 3) {
		fmt.Print(chunk, " ")
	}
	fmt.Println()
}
Output
[1 2 3 4 5]
[ab ab ab]
[1 2 3] [4 5 6] [7]

Iterating

A few functions connect slices with iterators (lesson 50): slices.All and slices.Values produce a slice's elements, slices.Backward walks from the end, and slices.Collect and slices.Sorted gather an iterator's values into a new slice:

GO
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	steps := []string{"mix", "bake", "cool"}
	for i, s := range slices.Backward(steps) {
		fmt.Print(i, ":", s, " ")
	}
	fmt.Println()

	ages := map[string]int{"cleo": 41, "ana": 34, "ben": 17}
	fmt.Println(slices.Sorted(maps.Keys(ages)))
	fmt.Println(len(slices.Collect(maps.Values(ages))))
}
Output
2:cool 1:bake 0:mix
[ana ben cleo]
3

Quick reference

TaskFunctions
SearchContains, Index, ContainsFunc, IndexFunc, BinarySearch
CompareEqual, Compare, EqualFunc
OrderSort, SortFunc, SortStableFunc, IsSorted, Reverse, Min, Max
ModifyInsert, Delete, DeleteFunc, Replace, Compact
BuildClone, Concat, Repeat, Grow, Clip
IterateAll, Values, Backward, Chunk, Collect, Sorted

Try it yourself

Given two guest lists, print everyone invited, sorted and without duplicates, and say whether "Dev" is on it.

Try it yourself · main.go
Edit the code, copy it into main.go in a new folder and run it with go run main.go (Go 1.27 or later). How to install Go
Output
[Ana Ben Cleo Dev Eli] 5
Dev invited: true
Next: maps.