Go slices.Contains
Test whether at least one item has the target price.
A simple example
slices.Contains
- Start with 1, 2, 3
- Do this Look for 2
- Result Found
Syntax
slices.Contains(prices, 3)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goCheck for a price in a sale list
A retailer checks a list of prices for a particular offer. Decide whether the question requires the presence of the price, its position or the number of occurrences before interpreting the result.
package main
import (
"fmt"
"slices"
)
func main() {
prices := []int{8, 3, 12, 3}
if slices.Contains(prices, 3) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
yes
Two prices are three, so a membership check succeeds. Only one match is required.
Check a badge at equipment pickup
The media desk releases cameras to students whose badge number is on the pickup list. Badge 204 is on the sheet between 101 and 305. The volunteer must match a whole number before handing out a camera.
package main
import (
"fmt"
"slices"
)
func main() {
badges := []int{101, 204, 305}
if slices.Contains(badges, 204) {
fmt.Println("Release camera")
} else {
fmt.Println("Check roster")
}
}
Release camera
The list contains badge 204, so the volunteer can release the camera. The recorded numbers identify students individually.
Check an equipment loan
The school loans projectors to registered classrooms. A volunteer checks for a whole identifier before releasing equipment. Does the requested identifier occur in the list?
What to watch for
Membership answers a yes-or-no question. Use a count when you need the number of matches.