package slices
Import Path
slices (on go.dev)
Dependency Relation
imports 3 packages, and imported by one package
Involved Source Files
Package slices defines various functions useful with slices of any type.
sort.go
zsortanyfunc.go
zsortordered.go
Code Examples
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"Alice", "Bob", "Vera"}
n, found := slices.BinarySearch(names, "Vera")
fmt.Println("Vera:", n, found)
n, found = slices.BinarySearch(names, "Bill")
fmt.Println("Bill:", n, found)
}
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type Person struct {
Name string
Age int
}
people := []Person{
{"Alice", 55},
{"Bob", 24},
{"Gopher", 13},
}
n, found := slices.BinarySearchFunc(people, Person{"Bob", 0}, func(a, b Person) int {
return cmp.Compare(a.Name, b.Name)
})
fmt.Println("Bob:", n, found)
}
package main
import (
"fmt"
"slices"
)
func main() {
seq := []int{0, 1, 1, 2, 3, 5, 8}
seq = slices.Compact(seq)
fmt.Println(seq)
}
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
names := []string{"bob", "Bob", "alice", "Vera", "VERA"}
names = slices.CompactFunc(names, func(a, b string) bool {
return strings.ToLower(a) == strings.ToLower(b)
})
fmt.Println(names)
}
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"Alice", "Bob", "Vera"}
fmt.Println("Equal:", slices.Compare(names, []string{"Alice", "Bob", "Vera"}))
fmt.Println("V < X:", slices.Compare(names, []string{"Alice", "Bob", "Xena"}))
fmt.Println("V > C:", slices.Compare(names, []string{"Alice", "Bob", "Cat"}))
fmt.Println("3 > 2:", slices.Compare(names, []string{"Alice", "Bob"}))
}
package main
import (
"cmp"
"fmt"
"slices"
"strconv"
)
func main() {
numbers := []int{0, 43, 8}
strings := []string{"0", "0", "8"}
result := slices.CompareFunc(numbers, strings, func(n int, s string) int {
sn, err := strconv.Atoi(s)
if err != nil {
return 1
}
return cmp.Compare(n, sn)
})
fmt.Println(result)
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, -10, 8}
hasNegative := slices.ContainsFunc(numbers, func(n int) bool {
return n < 0
})
fmt.Println("Has a negative:", hasNegative)
hasOdd := slices.ContainsFunc(numbers, func(n int) bool {
return n%2 != 0
})
fmt.Println("Has an odd number:", hasOdd)
}
package main
import (
"fmt"
"slices"
)
func main() {
letters := []string{"a", "b", "c", "d", "e"}
letters = slices.Delete(letters, 1, 4)
fmt.Println(letters)
}
package main
import (
"fmt"
"slices"
)
func main() {
seq := []int{0, 1, 1, 2, 3, 5, 8}
seq = slices.DeleteFunc(seq, func(n int) bool {
return n%2 != 0 // delete the odd numbers
})
fmt.Println(seq)
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, 8}
fmt.Println(slices.Equal(numbers, []int{0, 42, 8}))
fmt.Println(slices.Equal(numbers, []int{10}))
}
package main
import (
"fmt"
"slices"
"strconv"
)
func main() {
numbers := []int{0, 42, 8}
strings := []string{"000", "42", "0o10"}
equal := slices.EqualFunc(numbers, strings, func(n int, s string) bool {
sn, err := strconv.ParseInt(s, 0, 64)
if err != nil {
return false
}
return n == int(sn)
})
fmt.Println(equal)
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, 8}
fmt.Println(slices.Index(numbers, 8))
fmt.Println(slices.Index(numbers, 7))
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, -10, 8}
i := slices.IndexFunc(numbers, func(n int) bool {
return n < 0
})
fmt.Println("First negative at index", i)
}
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"Alice", "Bob", "Vera"}
names = slices.Insert(names, 1, "Bill", "Billie")
names = slices.Insert(names, len(names), "Zac")
fmt.Println(names)
}
package main
import (
"fmt"
"slices"
)
func main() {
fmt.Println(slices.IsSorted([]string{"Alice", "Bob", "Vera"}))
fmt.Println(slices.IsSorted([]int{0, 2, 1}))
}
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
func main() {
names := []string{"alice", "Bob", "VERA"}
isSortedInsensitive := slices.IsSortedFunc(names, func(a, b string) int {
return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
})
fmt.Println(isSortedInsensitive)
fmt.Println(slices.IsSorted(names))
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, -10, 8}
fmt.Println(slices.Max(numbers))
}
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type Person struct {
Name string
Age int
}
people := []Person{
{"Gopher", 13},
{"Alice", 55},
{"Vera", 24},
{"Bob", 55},
}
firstOldest := slices.MaxFunc(people, func(a, b Person) int {
return cmp.Compare(a.Age, b.Age)
})
fmt.Println(firstOldest.Name)
}
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{0, 42, -10, 8}
fmt.Println(slices.Min(numbers))
}
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type Person struct {
Name string
Age int
}
people := []Person{
{"Gopher", 13},
{"Bob", 5},
{"Vera", 24},
{"Bill", 5},
}
firstYoungest := slices.MinFunc(people, func(a, b Person) int {
return cmp.Compare(a.Age, b.Age)
})
fmt.Println(firstYoungest.Name)
}
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"Alice", "Bob", "Vera", "Zac"}
names = slices.Replace(names, 1, 3, "Bill", "Billie", "Cat")
fmt.Println(names)
}
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"alice", "Bob", "VERA"}
slices.Reverse(names)
fmt.Println(names)
}
package main
import (
"fmt"
"slices"
)
func main() {
smallInts := []int8{0, 42, -10, 8}
slices.Sort(smallInts)
fmt.Println(smallInts)
}
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
func main() {
names := []string{"Bob", "alice", "VERA"}
slices.SortFunc(names, func(a, b string) int {
return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
})
fmt.Println(names)
}
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type Person struct {
Name string
Age int
}
people := []Person{
{"Gopher", 13},
{"Alice", 55},
{"Bob", 24},
{"Alice", 20},
}
slices.SortFunc(people, func(a, b Person) int {
if n := cmp.Compare(a.Name, b.Name); n != 0 {
return n
}
// If names are equal, order by age
return cmp.Compare(a.Age, b.Age)
})
fmt.Println(people)
}
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type Person struct {
Name string
Age int
}
people := []Person{
{"Gopher", 13},
{"Alice", 20},
{"Bob", 24},
{"Alice", 55},
}
// Stable sort by name, keeping age ordering of Alices intact
slices.SortStableFunc(people, func(a, b Person) int {
return cmp.Compare(a.Name, b.Name)
})
fmt.Println(people)
}
Package-Level Functions (total 29)
Type Parameters:
S: ~[]E
E: cmp.Ordered
BinarySearch searches for target in a sorted slice and returns the position
where target is found, or the position where target would appear in the
sort order; it also returns a bool saying whether the target is really found
in the slice. The slice must be sorted in increasing order.
Type Parameters:
S: ~[]E
E: any
T: any
BinarySearchFunc works like [BinarySearch], but uses a custom comparison
function. The slice must be sorted in increasing order, where "increasing"
is defined by cmp. cmp should return 0 if the slice element matches
the target, a negative number if the slice element precedes the target,
or a positive number if the slice element follows the target.
cmp must implement the same ordering as the slice, such that if
cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice.
Type Parameters:
S: ~[]E
E: any
Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
Type Parameters:
S: ~[]E
E: any
Clone returns a copy of the slice.
The elements are copied using assignment, so this is a shallow clone.
Type Parameters:
S: ~[]E
E: comparable
Compact replaces consecutive runs of equal elements with a single copy.
This is like the uniq command found on Unix.
Compact modifies the contents of the slice s and returns the modified slice,
which may have a smaller length.
When Compact discards m elements in total, it might not modify the elements
s[len(s)-m:len(s)]. If those elements contain pointers you might consider
zeroing those elements so that objects they reference can be garbage collected.
Type Parameters:
S: ~[]E
E: any
CompactFunc is like [Compact] but uses an equality function to compare elements.
For runs of elements that compare equal, CompactFunc keeps the first one.
Type Parameters:
S: ~[]E
E: cmp.Ordered
Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair
of elements. The elements are compared sequentially, starting at index 0,
until one element is not equal to the other.
The result of comparing the first non-matching elements is returned.
If both slices are equal until one of them ends, the shorter slice is
considered less than the longer one.
The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.
Type Parameters:
S1: ~[]E1
S2: ~[]E2
E1: any
E2: any
CompareFunc is like [Compare] but uses a custom comparison function on each
pair of elements.
The result is the first non-zero result of cmp; if cmp always
returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2),
and +1 if len(s1) > len(s2).
Type Parameters:
S: ~[]E
E: comparable
Contains reports whether v is present in s.
Type Parameters:
S: ~[]E
E: any
ContainsFunc reports whether at least one
element e of s satisfies f(e).
Type Parameters:
S: ~[]E
E: any
Delete removes the elements s[i:j] from s, returning the modified slice.
Delete panics if s[i:j] is not a valid slice of s.
Delete is O(len(s)-j), so if many items must be deleted, it is better to
make a single call deleting them all together than to delete one at a time.
Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
elements contain pointers you might consider zeroing those elements so that
objects they reference can be garbage collected.
Type Parameters:
S: ~[]E
E: any
DeleteFunc removes any elements from s for which del returns true,
returning the modified slice.
When DeleteFunc removes m elements, it might not modify the elements
s[len(s)-m:len(s)]. If those elements contain pointers you might consider
zeroing those elements so that objects they reference can be garbage
collected.
Type Parameters:
S: ~[]E
E: comparable
Equal reports whether two slices are equal: the same length and all
elements equal. If the lengths are different, Equal returns false.
Otherwise, the elements are compared in increasing index order, and the
comparison stops at the first unequal pair.
Floating point NaNs are not considered equal.
Type Parameters:
S1: ~[]E1
S2: ~[]E2
E1: any
E2: any
EqualFunc reports whether two slices are equal using an equality
function on each pair of elements. If the lengths are different,
EqualFunc returns false. Otherwise, the elements are compared in
increasing index order, and the comparison stops at the first index
for which eq returns false.
Type Parameters:
S: ~[]E
E: any
Grow increases the slice's capacity, if necessary, to guarantee space for
another n elements. After Grow(n), at least n elements can be appended
to the slice without another allocation. If n is negative or too large to
allocate the memory, Grow panics.
Type Parameters:
S: ~[]E
E: comparable
Index returns the index of the first occurrence of v in s,
or -1 if not present.
Type Parameters:
S: ~[]E
E: any
IndexFunc returns the first index i satisfying f(s[i]),
or -1 if none do.
Type Parameters:
S: ~[]E
E: any
Insert inserts the values v... into s at index i,
returning the modified slice.
The elements at s[i:] are shifted up to make room.
In the returned slice r, r[i] == v[0],
and r[i+len(v)] == value originally at r[i].
Insert panics if i is out of range.
This function is O(len(s) + len(v)).
Type Parameters:
S: ~[]E
E: any
IsSortedFunc reports whether x is sorted in ascending order, with cmp as the
comparison function as defined by [SortFunc].
Type Parameters:
S: ~[]E
E: cmp.Ordered
Max returns the maximal value in x. It panics if x is empty.
For floating-point E, Max propagates NaNs (any NaN value in x
forces the output to be NaN).
Type Parameters:
S: ~[]E
E: any
MaxFunc returns the maximal value in x, using cmp to compare elements.
It panics if x is empty. If there is more than one maximal element
according to the cmp function, MaxFunc returns the first one.
Type Parameters:
S: ~[]E
E: cmp.Ordered
Min returns the minimal value in x. It panics if x is empty.
For floating-point numbers, Min propagates NaNs (any NaN value in x
forces the output to be NaN).
Type Parameters:
S: ~[]E
E: any
MinFunc returns the minimal value in x, using cmp to compare elements.
It panics if x is empty. If there is more than one minimal element
according to the cmp function, MinFunc returns the first one.
Type Parameters:
S: ~[]E
E: any
Replace replaces the elements s[i:j] by the given v, and returns the
modified slice. Replace panics if s[i:j] is not a valid slice of s.
Type Parameters:
S: ~[]E
E: any
Reverse reverses the elements of the slice in place.
Type Parameters:
S: ~[]E
E: cmp.Ordered
Sort sorts a slice of any ordered type in ascending order.
When sorting floating-point numbers, NaNs are ordered before other values.
Type Parameters:
S: ~[]E
E: any
SortFunc sorts the slice x in ascending order as determined by the cmp
function. This sort is not guaranteed to be stable.
cmp(a, b) should return a negative number when a < b, a positive number when
a > b and zero when a == b.
SortFunc requires that cmp is a strict weak ordering.
See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.
Type Parameters:
S: ~[]E
E: any
SortStableFunc sorts the slice x while keeping the original order of equal
elements, using cmp to compare elements in the same way as [SortFunc].
![]() |
The pages are generated with Golds v0.6.6. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |