Slices, 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.
Example. This program creates 3 different types of slices, and uses the methods from the "slices" module on them. It uses Contains, Index, and ContainsFunc.
Part 1 We create a slice of 3 strings. We use slices.Contains and try to find the "frog" value, which returns true.
Part 2 The slices.Index function returns the index of a found value, or the special value -1 if no matching value is found in the slice.
Part 3 With 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 29, 2024 (edit link).