slices

Guided tour · Collections · pkg.go.dev →

Generic slice operations (Go 1.21+). The modern answer to 'does stdlib have a Contains?' — yes.

Generic slice helpers (Go 1.21+). Sort, search, mutate, and convert slices without writing the loop yourself.

Sort ascending
slices.Sort(nums)
Sort by custom key
slices.SortFunc(users, func(a, b User) int {
    return cmp.Compare(a.Age, b.Age)
})
Contains / Index
slices.Contains(s, v); slices.Index(s, v)
Reverse in place
slices.Reverse(s)
Remove dup adjacent (sort first)
slices.Sort(s)
s = slices.Compact(s)
Insert / delete
s = slices.Insert(s, i, v)
s = slices.Delete(s, i, j)
Min / max
slices.Min(s); slices.Max(s)
Clone (avoid sharing backing array)
cp := slices.Clone(s)

Search and membership

Contains, Index

s := []string{"go", "rust", "ts"}
slices.Contains(s, "rust")  // true
slices.Index(s, "rust")     // 1
slices.Index(s, "zig")      // -1

ContainsFunc / IndexFunc — predicate variants

nums := []int{2, 4, 6, 9}
slices.ContainsFunc(nums, func(n int) bool { return n%2 == 1 }) // true

Min, Max, MinFunc, MaxFunc

Min/Max panic on an empty slice. Use MinFunc/MaxFunc with cmp.Compare-style functions for custom ordering.

slices.Min([]int{3, 1, 2})  // 1
slices.Max([]int{3, 1, 2})  // 3

Sorting and ordering

Sort / SortStable / SortFunc

Sort works on any ordered type. SortFunc takes a cmp function returning -1/0/+1 — use cmp.Compare.

s := []int{3, 1, 4, 1, 5}
slices.Sort(s)
fmt.Println(s)

type P struct{ Name string; Age int }
people := []P{{"A", 40}, {"B", 30}}
slices.SortFunc(people, func(a, b P) int {
    return cmp.Compare(a.Age, b.Age)
})

BinarySearch

s := []int{1, 3, 5, 7}
i, found := slices.BinarySearch(s, 5)
fmt.Println(i, found)  // 2 true

IsSorted / IsSortedFunc

slices.IsSorted([]int{1, 2, 3})  // true

Mutation

These modify the input slice in place and return the updated slice (length may change).

Insert, Delete, Replace

s := []int{1, 2, 5}
s = slices.Insert(s, 2, 3, 4)       // [1 2 3 4 5]
s = slices.Delete(s, 1, 3)          // remove indices [1,3) → [1 4 5]
s = slices.Replace(s, 0, 1, 9, 8)   // replace [0,1) with 9,8 → [9 8 4 5]

Reverse

s := []int{1, 2, 3}
slices.Reverse(s)   // [3 2 1]

Compact / CompactFunc — dedupe adjacent

Only removes *adjacent* duplicates — Sort first if you want full dedup.

s := []int{1, 1, 2, 3, 3, 3, 4}
s = slices.Compact(s)  // [1 2 3 4]

Copying and equality

Equal / EqualFunc

slices.Equal([]int{1, 2}, []int{1, 2})  // true

Clone — shallow copy

a := []int{1, 2, 3}
b := slices.Clone(a)
b[0] = 99
fmt.Println(a, b)  // [1 2 3] [99 2 3]

Concat (1.22+)

x := slices.Concat([]int{1, 2}, []int{3}, []int{4, 5})
fmt.Println(x)  // [1 2 3 4 5]

Iteration (1.23+)

All, Values, Backward — range-over-func

for i, v := range slices.All([]string{"a", "b", "c"}) {
    fmt.Println(i, v)
}
for v := range slices.Backward([]int{1, 2, 3}) {
    fmt.Println(v)
}