Package slices
suggest changeThe slices package (Go 1.21) is a set of generic functions that work on slices of any type. Before it existed, you wrote short loops and append idioms by hand to find, insert or delete elements. Those idioms are collected in Slice tricks. With slices most of them are a single, readable function call.
Functions were added in later releases:
- Go 1.21: the original package: search, insert, delete, compare, sort, min/max
- Go 1.22:
Concat;Deleteand friends zero the elements they remove - Go 1.23:
Repeatand the iterator functionsAll,Values,Backward,Collect,AppendSeq,Sorted,SortedFunc,SortedStableFunc,Chunk
This article is a tour of the package grouped by task. Sorting and binary search (Sort, SortFunc, SortStableFunc, IsSorted, BinarySearch) are covered in Sorting and not repeated here.
Most functions come in two flavours: a plain one that uses == or <, and a Func variant that takes a function, for element types that aren't comparable or when you need a different notion of equality or order.
Searching
Contains reports whether a value is in the slice. Index returns the index of the first match, or -1:
package main
import (
"fmt"
"slices"
"strings"
)
type User struct {
Name string
Admin bool
}
func main() {
langs := []string{"go", "rust", "zig", "go"}
fmt.Println(slices.Contains(langs, "zig"))
fmt.Println(slices.Contains(langs, "java"))
// index of the first match, -1 if not found
fmt.Println(slices.Index(langs, "go"))
fmt.Println(slices.Index(langs, "java"))
// the Func variants take a predicate
hasLong := slices.ContainsFunc(langs, func(s string) bool {
return len(s) > 3
})
fmt.Println(hasLong)
users := []User{{"alice", false}, {"bob", true}, {"carol", true}}
i := slices.IndexFunc(users, func(u User) bool { return u.Admin })
fmt.Println(i, users[i].Name)
// case-insensitive search
j := slices.IndexFunc(langs, func(s string) bool {
return strings.EqualFold(s, "RUST")
})
fmt.Println(j)
}
true
false
0
-1
true
1 bob
1
Contains and Index require a comparable element type. For structs with slice fields, for a match on one field, or for a case-insensitive search use ContainsFunc and IndexFunc.
All of these do a linear O(n) scan. If you search a large slice many times, sort it and use slices.BinarySearch (see Sorting) or build a map.
Inserting, deleting and replacing
Insert, Delete, DeleteFunc and Replace modify a slice and return the result. Always assign the result back, the same way you do with append:
package main
import (
"fmt"
"slices"
)
func main() {
s := []string{"a", "b", "c", "d", "e"}
// insert one or more values before index i
s = slices.Insert(s, 1, "X", "Y")
fmt.Println(s)
// insert at len(s) appends
s = slices.Insert(s, len(s), "end")
fmt.Println(s)
// insert another slice
s = slices.Insert(s, 0, []string{"p", "q"}...)
fmt.Println(s)
// delete s[i:j]
s = slices.Delete(s, 0, 2)
fmt.Println(s)
// delete a single element at i
i := slices.Index(s, "end")
s = slices.Delete(s, i, i+1)
fmt.Println(s)
// replace s[i:j] with any number of values
s = slices.Replace(s, 1, 3, "_")
fmt.Println(s)
// delete all elements matching a predicate
nums := []int{1, 2, 3, 4, 5, 6, 7, 8}
nums = slices.DeleteFunc(nums, func(n int) bool { return n%2 == 0 })
fmt.Println(nums)
}
[a X Y b c d e]
[a X Y b c d e end]
[p q a X Y b c d e end]
[a X Y b c d e end]
[a X Y b c d e]
[a _ b c d e]
[1 3 5 7]
What they do:
| function | does |
|---|---|
Insert(s, i, v...) |
inserts values before s[i]; i == len(s) appends |
Delete(s, i, j) |
removes s[i:j] |
DeleteFunc(s, del) |
removes every element for which del returns true |
Replace(s, i, j, v...) |
replaces s[i:j] with the values, which can be more or fewer than j-i |
Delete, DeleteFunc and Replace work in place: they shift the remaining elements and return a shorter slice that shares the backing array. Insert works in place when there's enough capacity, otherwise it allocates a new array, just like append.
DeleteFunc is the idiomatic way to filter a slice in place. Filter a slice and Remove elements from slice show how it's done by hand.
All of these are O(n) because they shift elements. To delete an element when you don't care about order, the O(1) trick of moving the last element into the hole (see Slice tricks) is still faster.
Delete clears the tail
Since Go 1.22 Delete, DeleteFunc, Compact, CompactFunc and Replace set the elements between the new length and the old length to the zero value:
package main
import (
"fmt"
"slices"
)
type Conn struct{ ID int }
func main() {
s := []int{1, 2, 3, 4, 5}
s = slices.Delete(s, 1, 3)
fmt.Println(s, len(s), cap(s))
// look at the whole backing array
fmt.Println(s[:cap(s)])
// with pointers, the old slots no longer keep Conns alive
conns := []*Conn{{1}, {2}, {3}}
conns = slices.Delete(conns, 0, 1)
fmt.Println(conns[0].ID, conns[1].ID, conns[:cap(conns)][2])
// the old slice header still sees the shared array
orig := []int{1, 2, 3, 4}
short := slices.Delete(orig, 0, 1)
fmt.Println(short, orig)
}
[1 4 5] 3 5
[1 4 5 0 0]
2 3 <nil>
[2 3 4] [2 3 4 0]
This matters for slices of pointers, or of structs that hold pointers. Before Go 1.22 the removed *Conn would still sit in the backing array after the new length, invisible but reachable, so the garbage collector couldn't free it. Now it's set to nil.
The last example shows the flip side: the original slice header orig still has length 4, so it sees the zeroed slot. After calling one of these functions, use only the returned slice.
Removing duplicates with Compact
Compact replaces runs of equal consecutive elements with a single copy. CompactFunc takes your own equality function and keeps the first element of each run:
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
// Compact removes consecutive duplicates
s := []int{1, 1, 2, 3, 3, 3, 1, 4, 4}
s = slices.Compact(s)
fmt.Println(s)
// CompactFunc decides what "equal" means
words := []string{"Go", "go", "GO", "zig", "Zig", "go"}
words = slices.CompactFunc(words, strings.EqualFold)
fmt.Println(words)
// collapse runs of spaces
text := []rune("too many spaces")
text = slices.CompactFunc(text, func(a, b rune) bool {
return a == ' ' && b == ' '
})
fmt.Println(string(text))
}
[1 2 3 1 4]
[Go zig go]
too many spaces
Compact only removes adjacent duplicates. To remove all duplicates, sort first. Sorting shows slices.Sort followed by slices.Compact. If you have to keep the original order, track seen values in a map instead.
Reversing
Reverse reverses the elements in place:
package main
import (
"fmt"
"slices"
)
func main() {
s := []int{1, 2, 3, 4, 5}
slices.Reverse(s) // in place, returns nothing
fmt.Println(s)
// reversed copy, original untouched
orig := []string{"a", "b", "c"}
rev := slices.Clone(orig)
slices.Reverse(rev)
fmt.Println(orig, rev)
// reverse a part of a slice
t := []int{0, 1, 2, 3, 4, 5}
slices.Reverse(t[2:5])
fmt.Println(t)
}
[5 4 3 2 1]
[a b c] [c b a]
[0 1 4 3 2 5]
To loop over a slice from last to first without changing it, use slices.Backward (see below).
Copying and joining: Clone, Concat, Repeat
Clone returns a copy of a slice. Concat joins several slices into one new slice. Repeat returns a slice repeated count times:
package main
import (
"fmt"
"slices"
)
func main() {
a := []int{1, 2, 3}
b := slices.Clone(a)
b[0] = 100
fmt.Println(a, b)
// Clone is shallow: inner slices are shared
grid := [][]int{{1, 2}, {3, 4}}
g2 := slices.Clone(grid)
g2[0][0] = 99
fmt.Println(grid)
// nil stays nil, empty stays empty
var n []int
fmt.Println(slices.Clone(n) == nil, slices.Clone([]int{}) == nil)
// Concat joins any number of slices into a new one (Go 1.22)
all := slices.Concat([]int{1, 2}, []int{3}, nil, []int{4, 5})
fmt.Println(all)
// Repeat concatenates a slice with itself count times (Go 1.23)
fmt.Println(slices.Repeat([]string{"-"}, 5))
fmt.Println(slices.Repeat([]int{1, 0}, 3))
}
[1 2 3] [100 2 3]
[[99 2] [3 4]]
true false
[1 2 3 4 5]
[- - - - -]
[1 0 1 0 1 0]
Notes:
Cloneis shallow. It copies the elements, so for slices of slices, pointers or maps the copy shares the data they point to. See Duplicate a slice for a deep copy.Clonekeeps the difference between aniland an empty slice, which matters for code like JSON encoding wherenilbecomesnulland an empty slice becomes[].Concatallocates the result once with the right size. It's simpler and faster than a chain ofappend(a, b...)calls, and it never modifies its arguments:append(a, b...)can write intoa's spare capacity.Repeatpanics ifcountis negative or the result length overflows.
Capacity: Grow and Clip
Grow(s, n) makes sure that the slice has room for at least n more elements, so the next n appends don't allocate. Clip(s) removes unused capacity, which makes cap(s) == len(s):
package main
import (
"fmt"
"slices"
)
func main() {
// Grow guarantees room for n more elements without reallocating
s := []int{1, 2, 3}
s = slices.Grow(s, 100)
fmt.Println(len(s), cap(s) >= 103)
p := &s[0]
for i := range 100 {
s = append(s, i)
}
fmt.Println("same array:", p == &s[0])
// Clip removes unused capacity: cap becomes len
buf := make([]int, 3, 10)
part := slices.Clip(buf[:2])
fmt.Println(len(part), cap(part))
// why Clip matters: append on a sub-slice can overwrite the parent
data := []int{1, 2, 3, 4}
head := data[:2]
head = append(head, 99)
fmt.Println(data) // data[2] was overwritten
data = []int{1, 2, 3, 4}
head = slices.Clip(data[:2])
head = append(head, 99) // forced to allocate a new array
fmt.Println(data, head)
}
3 true
same array: true
2 2
[1 2 99 4]
[1 2 3 4] [1 2 99]
Use Grow when you know roughly how many elements you'll append to an existing slice; for a new slice make([]T, 0, n) does the same. See Optimize by pre-allocating slice.
Use Clip before you hand out a sub-slice of an array you keep using. append on a clipped slice can't write past its length, so it has to allocate a new array instead of silently overwriting your data.
Comparing: Equal and Compare
Slices don't support == (except comparison with nil). Equal compares the length and every element:
package main
import (
"fmt"
"math"
"slices"
"strings"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
// a == b is a compile error: slices can only be compared to nil
fmt.Println(slices.Equal(a, b))
fmt.Println(slices.Equal(a, []int{1, 2}))
// nil and empty slices are equal
var n []int
fmt.Println(slices.Equal(n, []int{}))
// NaN is not equal to itself
f := []float64{math.NaN()}
fmt.Println(slices.Equal(f, f))
// EqualFunc: custom equality, the element types can differ
names := []string{"Go", "ZIG"}
lower := []string{"go", "zig"}
fmt.Println(slices.EqualFunc(names, lower, strings.EqualFold))
ids := []int{1, 2, 3}
strs := []string{"1", "2", "3"}
fmt.Println(slices.EqualFunc(ids, strs, func(i int, s string) bool {
return fmt.Sprint(i) == s
}))
// Compare: lexicographic order, returns -1, 0 or +1
fmt.Println(slices.Compare([]int{1, 2, 3}, []int{1, 2, 4}))
fmt.Println(slices.Compare([]int{1, 2}, []int{1, 2, 0}))
fmt.Println(slices.Compare([]int{2}, []int{1, 9, 9}))
fmt.Println(slices.Compare([]string{"a", "b"}, []string{"a", "b"}))
}
true
false
true
false
true
true
-1
-1
1
0
Equaltreatsniland empty slices as equal. If the difference matters, checks == nilseparately.Equaluses==, so a slice containingNaNis not equal to itself.EqualFuncwith a function that treatsNaNs as equal fixes that.EqualFunccan compare slices of different element types, as long as the function knows how to compare them.Comparecompares element by element like strings are compared: the first difference decides, and if one slice is a prefix of the other, the shorter slice is smaller.CompareFuncis the custom version. They are handy as a tie-breaker in aslices.SortFunccomparison function.
Min and Max
Min and Max return the smallest and largest element of a slice of ordered values (cmp.Ordered: numbers and strings). MinFunc and MaxFunc take a comparison function:
package main
import (
"cmp"
"fmt"
"slices"
)
type Item struct {
Name string
Price int
}
func main() {
temps := []float64{21.5, 19.0, 25.3, 19.0}
fmt.Println(slices.Min(temps), slices.Max(temps))
items := []Item{
{"pen", 2}, {"book", 15}, {"mug", 8}, {"cap", 2}, {"lamp", 15},
}
byPrice := func(a, b Item) int { return cmp.Compare(a.Price, b.Price) }
// MinFunc and MaxFunc return the first of several equal elements
fmt.Println(slices.MinFunc(items, byPrice))
fmt.Println(slices.MaxFunc(items, byPrice))
// for 2 or 3 values use the built-in min and max (Go 1.21)
fmt.Println(min(3, 1, 2), max("a", "b"))
// Min and Max panic on an empty slice
defer func() { fmt.Println("recovered:", recover()) }()
var empty []int
_ = slices.Max(empty)
}
19 25.3
{pen 2}
{book 15}
1 b
recovered: slices.Max: empty list
Min and Max panic on an empty slice, so check len(s) > 0 first when the slice can be empty. If there are several minimal elements, MinFunc and MaxFunc return the first one. For a handful of separate values use the built-in min and max functions instead.
Iterator functions
Go 1.23 added range-over-func iterators, and slices has functions that turn a slice into an iterator and an iterator into a slice:
| function | does |
|---|---|
All(s) |
iter.Seq2[int, E] of index and element |
Values(s) |
iter.Seq[E] of elements |
Backward(s) |
iter.Seq2[int, E] from the last element to the first |
Chunk(s, n) |
iter.Seq[S] of consecutive sub-slices of up to n elements |
Collect(seq) |
a new slice with all values of seq |
AppendSeq(s, seq) |
s with all values of seq appended |
Sorted(seq), SortedFunc(seq, cmp), SortedStableFunc(seq, cmp) |
a new sorted slice with all values of seq |
All, Values and Backward are basic examples in Iterators and range over functions. The functions are more useful when combined with other iterators:
package main
import (
"fmt"
"iter"
"slices"
"strings"
)
// Filter returns an iterator over values of seq for which keep returns true.
func Filter[V any](seq iter.Seq[V], keep func(V) bool) iter.Seq[V] {
return func(yield func(V) bool) {
for v := range seq {
if keep(v) && !yield(v) {
return
}
}
}
}
func main() {
words := []string{"banana", "Apple", "cherry", "apple", "date"}
// Values -> filter -> Collect: a new slice of matching words
long := slices.Collect(Filter(slices.Values(words), func(s string) bool {
return len(s) > 5
}))
fmt.Println(long)
// Sorted collects and sorts in one step
fmt.Println(slices.Sorted(strings.SplitSeq("c,a,b", ",")))
// SortedFunc with a custom order
ci := slices.SortedFunc(slices.Values(words), func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
fmt.Println(ci)
// AppendSeq appends to an existing slice
out := slices.AppendSeq([]string{"fig"}, slices.Values(words[:2]))
fmt.Println(out)
// Chunk: process in batches of up to n elements
ids := []int{1, 2, 3, 4, 5, 6, 7}
for batch := range slices.Chunk(ids, 3) {
fmt.Println("batch:", batch)
}
}
[banana cherry]
[a b c]
[Apple apple banana cherry date]
[fig banana Apple]
batch: [1 2 3]
batch: [4 5 6]
batch: [7]
Values turns a slice into an iterator that any iterator-based function can use. Collect and Sorted turn the result back into a slice. Sorted accepts any iter.Seq, which is why slices.Sorted(maps.Keys(m)) is the standard way to get the sorted keys of a map. See Map, filter, and reduce for more helpers like Filter.
Chunk yields sub-slices of the original slice, without copying. That's ideal for sending items to an API or database in batches. Chunks are clipped, so appending to one allocates a new array instead of overwriting the next chunk, but changing an element of a chunk changes the original slice. Chunk panics if n is less than 1.
Backward is useful when you delete elements while looping. Deleting s[i] shifts only the elements after i, and those were already visited:
package main
import (
"fmt"
"slices"
)
func main() {
// Backward lets you delete while iterating: indexes before i don't move
s := []int{1, 2, 3, 4, 5, 6}
for i, v := range slices.Backward(s) {
if v%3 == 0 {
s = slices.Delete(s, i, i+1)
}
}
fmt.Println(s)
// usually DeleteFunc is simpler
t := []int{1, 2, 3, 4, 5, 6}
t = slices.DeleteFunc(t, func(v int) bool { return v%3 == 0 })
fmt.Println(t)
// forgetting to assign the result
u := []int{1, 2, 3, 4}
slices.Delete(u, 0, 1) // result discarded
fmt.Println(u)
// out-of-range indexes panic
defer func() { fmt.Println("recovered:", recover()) }()
u = slices.Insert(u, 10, 5)
}
[1 2 4 5]
[1 2 4 5]
[2 3 4 0]
recovered: runtime error: slice bounds out of range [10:4]
The third block shows the most common mistake with the package: calling a function that returns a new slice and ignoring the result. The slice u keeps its old length and you see the shifted elements plus the zeroed tail. go vet catches this:
$ go vet .
main.go:25:2: result of slices.Delete call not used
Named slice types
The functions are declared with a type parameter like S ~[]E, so they accept named slice types and return the same type, not the underlying []E. Methods on your type keep working on the result:
package main
import (
"fmt"
"slices"
"strings"
)
type Path []string
func (p Path) String() string { return "/" + strings.Join(p, "/") }
func main() {
p := Path{"usr", "local", "bin"}
// the results have type Path, not []string, so String() still works
q := slices.Insert(p, 2, "go")
fmt.Printf("%T %v\n", q, q)
r := slices.Clone(p)
fmt.Printf("%T %v\n", r, r)
all := slices.Concat(p, Path{"tool"})
fmt.Printf("%T %v\n", all, all)
}
main.Path /usr/local/go/bin
main.Path /usr/local/bin
main.Path /usr/local/bin/tool
Slice tricks and their slices equivalents
Many classic idioms from Slice tricks have a direct replacement:
| manual idiom | with slices |
|---|---|
b = append([]T(nil), a...) |
b = slices.Clone(a) |
a = append(a[:i], a[j:]...) |
a = slices.Delete(a, i, j) |
a = append(a[:i], a[i+1:]...) |
a = slices.Delete(a, i, i+1) |
a = append(a[:i], append([]T{x}, a[i:]...)...) |
a = slices.Insert(a, i, x) |
a = append(a[:i], append(b, a[i:]...)...) |
a = slices.Insert(a, i, b...) |
a = append(a, make([]T, n)...)[:len(a)] |
a = slices.Grow(a, n) |
| filter in place with a loop | a = slices.DeleteFunc(a, drop) |
| reverse with two indexes | slices.Reverse(a) |
| in-place deduplicate of a sorted slice | a = slices.Compact(a) |
batching with a[:n] in a loop |
for batch := range slices.Chunk(a, n) |
for _, v := range a { if v == x { ... } } |
slices.Contains(a, x), slices.Index(a, x) |
| a loop to find the largest element | slices.Max(a) |
a = append(a, b...) into a new slice |
c := slices.Concat(a, b) |
The library versions are tested, handle edge cases like i == len(s), and clear removed elements. Prefer them in new code.
Things to keep in mind
- functions that return a slice (
Insert,Delete,DeleteFunc,Replace,Compact,CompactFunc,Grow,Clip): assign it back,go vetwarns when you don't Reverse,Sortand friends work in place and return nothingDeleteand similar work in place and zero the removed tail (Go 1.22); the old slice header sees the zeroed elements- out-of-range indexes panic, as with ordinary slice expressions
Contains,IndexandIndexFuncare O(n); use a map or a sorted slice for frequent lookupsCompactremoves only adjacent duplicatesCloneis shallow and keepsnilasnilEqualconsidersniland empty slices equalMinandMaxpanic on an empty sliceChunkyields sub-slices that share memory with the original
Summary
- search with
Contains,Indexand theirFuncvariants - modify with
Insert,Delete,DeleteFunc,Replace,CompactandReverse - copy and join with
Clone,ConcatandRepeat; manage capacity withGrowandClip - compare with
EqualandCompare; find extremes withMinandMax - connect slices and iterators with
Values,All,Backward,Chunk,Collect,AppendSeqandSorted - for sorting and binary search see Sorting