slices

The Go slices package, including in-place Sort, Clone, Delete, Compact, and Reverse, with version notes relative to package sort.

The slices package was added to the standard library in Go 1.21. It is not a third-party module, and it is not the same as the built-in append, copy, len, cap, or the built-in min and max functions, which operate on individual comparable values rather than on a slice of values.

The older sort package remains in the standard library. sort.Strings, sort.Ints, and sort.Slice still work. For new code on Go 1.21 or later, slices.Sort and the other generic helpers on this page are the usual choice. Examples were checked with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
slices.Sort, slices.Contains, slices.Index, slices.MaxSort a slice in place, then search or take the maximum. Sort changes the existing slice; it does not allocate a sorted copy.
slices.Clone, slices.EqualCopy a slice into a new backing array, or compare two slices element by element.
slices.Delete, slices.Compact, slices.ReverseRemove a range, collapse consecutive duplicates, or reverse a slice in place. Assign the value returned by Delete and Compact; Reverse mutates the slice and returns nothing.
Compare map values with slices.SortUse the comma-ok lookup to restrict the comparison to keys in both maps. Sort the report after iterating because Go map iteration order can vary.

Sort, Contains, and Max

slices.Sort sorts a slice of a cmp.Ordered type in place and does not return a new slice. After the call, the variable you passed in holds the sorted elements. There is no slices.ToSorted helper in this package; clone first if you need to keep the original order.

slices.Max and slices.Min panic on an empty slice. The built-in max and min functions, also added in Go 1.21, take one or more scalar arguments and are a different API.

slices.Sort, slices.Contains, slices.Index, slices.Max

func Sort[S ~[]E, E cmp.Ordered](x S)
func Contains[S ~[]E, E comparable](s S, v E) bool
func Index[S ~[]E, E comparable](s S, v E) int
func Max[S ~[]E, E cmp.Ordered](s S) E

Sort a slice in place, then search or take the maximum. Sort changes the existing slice; it does not allocate a sorted copy.

ParameterDescription
x / sThe slice to sort, search, or reduce. Sort may not be called on a nil function or uncomparable element type; the element type must satisfy cmp.Ordered.
vThe value to search for in Contains and Index.

Returns: Sort has no return value. Contains returns whether v is present. Index returns the first index, or -1. Max returns the maximum element.

  • Equivalent older calls include sort.Ints and sort.Strings in package sort. Those are still valid; this page uses slices because the package is generic and covers more types with one function.
  • Index reports a byte-unrelated slice index. For [1 1 2 2 3], Index(..., 2) is 2.
go
package main

import (
	"fmt"
	"slices"
)

func main() {
	values := []int{3, 1, 2, 2, 1}
	slices.Sort(values)
	fmt.Println(values)
	fmt.Println(slices.Contains(values, 2), slices.Index(values, 2))
	fmt.Println(slices.Max(values))
}

Expected output

[1 1 2 2 3]
true 2
3

Related: package sort

Official documentation →

Clone and Equal

Clone returns a copy of the slice's elements. The original and the clone share no backing array, so assigning through one index does not change the other. Equal compares lengths and corresponding elements.

slices.Clone, slices.Equal

func Clone[S ~[]E, E any](s S) S
func Equal[S1 ~[]E, S2 ~[]E, E comparable](s1 S1, s2 S2) bool

Copy a slice into a new backing array, or compare two slices element by element.

ParameterDescription
s / s1 / s2The slices to copy or compare. Equal requires comparable element types.

Returns: Clone returns a new slice with the same length and elements. Clone(nil) returns nil. Equal returns whether both length and elements match.

  • Assigning clone[0] = 9 leaves the original src unchanged, which is the point of cloning before an in-place operation such as Sort or Reverse.
go
package main

import (
	"fmt"
	"slices"
)

func main() {
	src := []int{1, 2, 3}
	clone := slices.Clone(src)
	clone[0] = 9
	fmt.Println(src, clone)
	fmt.Println(slices.Equal([]int{1, 2}, []int{1, 2}))
}

Expected output

[1 2 3] [9 2 3]
true

Official documentation →

Delete, Compact, and Reverse

Delete, Compact, and Reverse modify the backing array of the slice you pass in. Reverse has no return value. Delete and Compact return the shortened slice; you must assign that result, because the new length is not written back into the original slice header.

On Go 1.24, both Delete and Compact zero the elements between the new length and the original length. That is the documented behavior of this version. Always use the returned length. Do not read elements past len(s) and expect the previous values to still be there.

slices.Delete, slices.Compact, slices.Reverse

func Delete[S ~[]E, E any](s S, i, j int) S
func Compact[S ~[]E, E comparable](s S) S
func Reverse[S ~[]E, E any](s S)

Remove a range, collapse consecutive duplicates, or reverse a slice in place. Assign the value returned by Delete and Compact; Reverse mutates the slice and returns nothing.

ParameterDescription
sThe slice to modify. Compact requires comparable elements and only collapses consecutive duplicates, so sort first if you want all duplicates removed.
i, jDelete removes s[i:j]. It panics if j > len(s) or s[i:j] is not a valid slice of s.

Returns: Delete and Compact return the modified slice, which may be shorter. Reverse has no result.

  • After Delete(s, 1, 3) on [a b c d], the result is [a d] with length 2. On Go 1.24 the unused tail of the original backing array is zeroed, so a cap() view shows empty strings rather than leftover "c" values.
  • Compact is in-place and, on Go 1.24, also zeroes the tail. The original variable still has the old capacity; the returned slice is the compact prefix.
  • If you still use an older Go 1.21 snapshot, check that version of the documentation before relying on the tail being cleared.
go
package main

import (
	"fmt"
	"slices"
)

func main() {
	values := []string{"a", "b", "c", "d"}
	values = slices.Delete(values, 1, 3)
	fmt.Printf("after=%q len=%d cap=%d backing=%q\n", values, len(values), cap(values), values[:cap(values)])

	compacted := []int{1, 1, 2, 2, 3}
	out := slices.Compact(compacted)
	fmt.Println(out, compacted)

	rev := []int{1, 2, 3}
	slices.Reverse(rev)
	fmt.Println(rev)
}

Expected output

after=["a" "d"] len=2 cap=4 backing=["a" "d" "" ""]
[1 2 3] [1 2 3 0 0]
[3 2 1]

Official documentation →

Report changed map values in a stable order

Go map iteration order can change from one run to the next. After collecting keys, slices.Sort makes the report deterministic. The comma-ok lookup is required when a missing integer key would otherwise look like 0.

Compare map values with slices.Sort

func Sort[S ~[]E, E cmp.Ordered](x S)

Use the comma-ok lookup to restrict the comparison to keys in both maps. Sort the report after iterating because Go map iteration order can vary.

  • This example is the original Go reference recipe; the section id is unchanged.
  • A lookup of a missing integer key yields 0. Check the presence flag before treating it as an explicit zero.
go
package main

import (
	"fmt"
	"slices"
)

func main() {
	before := map[string]int{"port": 80, "retries": 3, "timeout": 10}
	after := map[string]int{"port": 8080, "timeout": 0}
	var changed []string
	for key, old := range before {
		if current, ok := after[key]; ok && current != old {
			changed = append(changed, key)
		}
	}
	slices.Sort(changed)
	fmt.Println(changed)
}

Expected output

[port timeout]

Related: Original recipe on the Go overview, Index expressions in the language spec

Official documentation →