Learn Go← Dashboard

Fixed-size arrays and the workhorse slice type.

The slices Package

Go 1.21 added a generic slices package that replaces the hand-rolled loops everyone used to write for sort, search, insert, delete, and equality. If you still see sort.Slice(...) in code review, this is the modern replacement.

Sort, search, and contains

go playground
Loading...

slices.Sort works on any slice whose element type is cmp.Ordered — numbers, strings, anything with <. For custom ordering use slices.SortFunc:

type Person struct{ Name string; Age int }
people := []Person{{"Bo", 30}, {"Al", 24}}
slices.SortFunc(people, func(a, b Person) int {
    return a.Age - b.Age   // negative = a first, like cmp.Compare
})

SortFunc takes a function returning an int<0, 0, >0 like a three-way compare. cmp.Compare from the cmp package gives you that for ordered types.

Insert and delete (in place)

go playground
Loading...

Both return a new slice (possibly with a new backing array), same as append. Always assign the result back.

Compare, copy, reverse

slices.Equal([]int{1, 2}, []int{1, 2})     // true
slices.Clone(s)                            // independent copy
slices.Reverse(s)                          // in-place reverse
slices.Concat(a, b, c)                     // since Go 1.22
slices.Max(nums)                           // panics on empty slice
slices.Min(nums)

Equal walks both slices element-by-element. For deep comparison of slices of structs containing slices, you still want reflect.DeepEqual or a custom check.

A handy idiom: dedupe a sorted slice

slices.Sort(xs)
xs = slices.Compact(xs)   // collapses runs of equal adjacent values

Compact is O(n) and only removes adjacent duplicates — that's why you sort first.

`slices.Sort(xs)` works on `xs []int` but `slices.SortFunc` is required for `xs []Person`. Why?