Contains
Let's consider another common collection operation: contains.
In Go, lists of things are often stored in a slice. Wouldn't it be nice if Go provided a contains method to tell us whether the item we are looking for is contained in the slice? Since there is no generic contains method for working with lists of items in Go, let's implement one to iterate over a collection of car objects.
Iterating over a collection of cars
First, let's create a Car struct that we can use to define the Cars collection as a slice of Car. Later, we'll create a Contains() method to try out on our collection:
package main
type Car struct {
Make string
Model string
}
type Cars []*CarHere's our Contains() implementation. Contains() is a method for Cars. It takes a modelName string, for example, Highlander, and returns true if it was found in the slice of Cars:
func (cars Cars) Contains(modelName string) bool {
for _, a := range cars {
if a.Model == modelName {
return...