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) ESort a slice in place, then search or take the maximum. Sort changes the existing slice; it does not allocate a sorted copy.
| Parameter | Description |
|---|---|
x / s | The 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. |
v | The 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.
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
3Related: package sort