Go Reference ยท Collections: sort, slices, maps
Go slices.Contains() and slices.Index() functions
Reference for Go slices.Contains, ContainsFunc, Index and IndexFunc: check whether a slice holds a value, find its position, and the cost of linear search.
slices.Contains(s, v) reports whether the slice s has an element equal to v. slices.Index(s, v) returns the position of the first such element, or -1 if there is none. The Func versions, ContainsFunc and IndexFunc, take a predicate instead of a value, so you can search by a condition or a field.
All four do a linear scan from the start. The element type must be comparable for Contains and Index; there is no restriction for the Func forms. They were added to the standard library in Go 1.21.
fmt.Println(slices.Contains([]string{"a", "b"}, "b")) // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Contains[S ~[]E, E comparable](s S, v E) bool func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool func Index[S ~[]E, E comparable](s S, v E) int func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int
| Name | Description |
|---|---|
s |
The slice to search. May be nil or empty. |
v |
The value to look for, compared with ==. |
f |
Predicate called for elements in order; the search stops at the first true. |
Returns: Contains and ContainsFunc return a bool. Index and IndexFunc return the index of the first match, or -1.
Edge cases: an empty or nil slice gives false / -1. The functions never panic, unless comparing two interface values that hold uncomparable dynamic types (such as slices), which panics at run time.
Usage notes
- Linear time. Each call is
O(n). If you test membership many times on a big collection, build amap[T]struct{}once or keep the slice sorted and useslices.BinarySearch. - Equality is
==: strings and numbers compare by value, pointers by address, structs field by field. Slices, maps and functions are not comparable, so they cannot be elements forContains; useContainsFuncorslices.EqualFunc. - NaN never matches, because
NaN != NaN. UseContainsFunc(s, math.IsNaN)to test for it. - Last occurrence: there is no
LastIndex. Loop backwards withslices.Backwardor search the reversed copy. - Replaces the hand-written loop:
for _, x := range s { if x == v { return true } }is exactlyContains. - Index of all matches needs your own loop;
Indexreports only the first one. - Strings: for text inside one string use
strings.Containsandstrings.Indexinstead; these functions are for slices of values.