Go

slices package — Modern Helpers

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`slices` (Go 1.21+) ships the iteration helpers everyone wrote by hand for years: Contains, Index, Sort, SortFunc, BinarySearch, Clone, Reverse, Equal, Max/Min.
Go
Raw
package main

import (
    "cmp"
    "fmt"
    "slices"
)

func main() {
    nums := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}

    fmt.Println(slices.Contains(nums, 9))         // true
    fmt.Println(slices.Index(nums, 4))            // 2 (first occurrence)
    fmt.Println(slices.Max(nums))                 // 9
    fmt.Println(slices.Min(nums))                 // 1

    // In-place ascending sort
    slices.Sort(nums)
    fmt.Println(nums)                              // [1 1 2 3 3 4 5 5 5 6 9]

    // Binary search on a sorted slice
    pos, ok := slices.BinarySearch(nums, 5)
    fmt.Println(pos, ok)                           // 6 true

    // Custom sort
    type User struct{ Name string; Age int }
    users := []User{{"Bob", 30}, {"Alice", 25}, {"Cara", 35}}
    slices.SortFunc(users, func(a, b User) int {
        return cmp.Compare(a.Age, b.Age)           // sort by age ascending
    })
    fmt.Println(users)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.