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
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]) }
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:
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)) }
true false -1 1 0
Min, max and sorting
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) }
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
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) }
[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:
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) }
[api go web]
Building slices
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() }
[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:
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)))) }
2:cool 1:bake 0:mix [ana ben cleo] 3
Quick reference
| Task | Functions |
|---|---|
| Search | Contains, Index, ContainsFunc, IndexFunc, BinarySearch |
| Compare | Equal, Compare, EqualFunc |
| Order | Sort, SortFunc, SortStableFunc, IsSorted, Reverse, Min, Max |
| Modify | Insert, Delete, DeleteFunc, Replace, Compact |
| Build | Clone, Concat, Repeat, Grow, Clip |
| Iterate | All, 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.
[Ana Ben Cleo Dev Eli] 5 Dev invited: true