Use slices.Contains to check if a value exists in a Go slice.
Use the slices.Contains function from the slices package to check if a slice contains a specific value. This function returns true if the value exists in the slice, and false otherwise.
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
if slices.Contains(nums, 3) {
fmt.Println("Found 3")
}
}
Checking if a slice contains a value in Go is a built-in tool that scans a list of items to see if a specific one is inside it. It saves you from writing a loop to check every item manually. Think of it like asking a librarian if a specific book is on a shelf without having to look at every single book yourself.