slices package
The slices package (Go 1.21+) is a generic toolkit for []T: sort, search, clip, compact, grow, delete, and compare. It replaces many sort.Slice and hand-rolled loops with typed helpers.
Detailed Explanation
For years every module wrote contains, index, and sort by key again. slices is that file in the standard library. slices.Contains(ids, 7), slices.Index(names, "ada"), slices.Sort(ids), slices.SortFunc(users, cmp), slices.BinarySearch(sorted, x) are the everyday calls. The element type is a type parameter, so you keep []User instead of interface{}.
Sort and search. slices.Sort works for cmp.Ordered types. slices.SortFunc takes a cmp.Compare-style function that returns -1, 0, 1. slices.SortStableFunc is the stable variant. slices.BinarySearch and slices.BinarySearchFunc require a sorted slice and return (index, found).
Edit helpers. slices.Delete(s, i, j) removes s[i:j] and zeros the tail (since Go 1.22) so leftover pointers do not leak. slices.Replace, slices.Insert, slices.Clip (drop unused cap), slices.Grow, slices.Compact (unique consecutive equals), and slices.Clone cover the rest of the "I would have used append and copy" space.
Compare. slices.Equal compares two slices element-wise. slices.Compare returns the lexicographic order. slices.EqualFunc lets you define equality for structs.
Not a substitute for []T idioms. Building a slice with append is still normal. slices is for operations on an existing slice. It does not offer map/filter as named functions; a loop or a small generic helper in your module is still the Go style.
What it costs. Same as the loops you would have written, with less chance of an off-by-one. Sort is O(n log n). Index is O(n). Prefer slices over sort.Slice in new code so the less function is a typed cmp on values, not indexes you can mix up.
Code Examples
package main
import (
"cmp"
"fmt"
"slices"
)
type User struct {
Name string
Age int
}
func main() {
ids := []int{3, 1, 2}
slices.Sort(ids)
fmt.Println(ids, slices.Contains(ids, 2))
users := []User{{"b", 20}, {"a", 30}}
slices.SortFunc(users, func(a, b User) int {
return cmp.Compare(a.Name, b.Name)
})
fmt.Println(users)
}func without(s []int, i int) []int {
return slices.Delete(s, i, i+1)
}Common Gotchas
`Delete` returns a new header and may alias the same array
assign the result, same as `append`.
`BinarySearch` on an unsorted slice is wrong without panicking
sort first.
`sort.Slice` is not deprecated
it still works. `slices` is clearer for typed elements.
`slices` is not the `[]T` built-in type
the package name collides with how people say "slices" in English. Import it as `slices`.