Contains
Suppose we have a slice in our Go program, and it can have any type of elements—strings, ints, uints. We can use the slices module and its Contains
method to search it.
Instead of writing a for-range
loop for every single slice type, we can just use the slices module. This can reduce the size of code, making it easier to read and review.
This program creates 3 different types of slices, and uses the methods from the "slices" module on them. It uses Contains
, Index
, and ContainsFunc
.
slices.Contains
and try to find the "frog" value, which returns true.slices.Index
function returns the index of a found value, or the special value -1 if no matching value is found in the slice.ContainsFunc
(and IndexFunc
) we must provide a second argument that is a func
that returns bool
and checks each element.package main
import (
"fmt"
"slices"
)
func main() {
// Part 1: use Contains on a slice of strings, and with both existing and non-existing argument.
slice := []string{"bird", "frog", "dog"}
result := slices.Contains(slice, "frog")
fmt.Println("Contains frog:", result)
fmt.Println("Contains ?:", slices.Contains(slice, "?"))
// Part 2: use Index on int slice.
slice2 := []int{10, 20, 30}
result2 := slices.Index(slice2, 20)
fmt.Println("Index 20:", result2)
fmt.Println("Index 10000:", slices.Index(slice2, 1000))
// Part 3: use ContainsFunc on a uint slice with a lambda function argument.
slice3 := []uint{10, 20, 30}
result3 := slices.ContainsFunc(slice3, func(value uint) bool {
return value >= 30
})
fmt.Println("ContainsFunc:", result3)
}Contains frog: true
Contains ?: false
Index 20: 1
Index 10000: -1
ContainsFunc: true
The slices package allows us to use convenient, tested methods to search and even manipulate slices. These methods are similar in concept to the strings.Index
and Contains
funcs.