Learning Functional Programming in Go
上QQ阅读APP看书,第一时间看更新

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 []*Car

Here'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 true
}
}
return false
}

This seems simple enough to implement, but what happens when we are given a list of boats or boxes to iterate over? That's right, we'll have to reimplement the Contains() method for each one. That's ugly!  

This is yet another situation where it would be nice to have generics.