In the last chapter, we discussed some of the benefits of generics:
- Type safety
- Eliminates the need to write repetitive, boilerplate code
- Reuses and shares code for different types
- Enforces consistent APIs across different types
- Time spent optimizing generic code has more impact
- Don’t need to re-implement algorithms that are hard to get right
- Able to specify domain constraints
Given the following type definitions:
type Car struct { Make, Model string Price Dollars } type Truck struct { Make, Model string BedSize int Price Dollars } price := func (c T) Dollars { return c.Price }
Instead of writing both of these:
type CarSlice []Car func (rcv CarSlice) SumDollars(fn func(Car) Dollars) (result Dollars) { for _, v := range rcv { result += fn(v) } return } type TruckSlice []Truck func (rcv TruckSlice) SumDollars(fn func(Truck) Dollars) (result Dollars) { for _, v := range rcv { result += fn(v) } return }
We can print the price sums as follows:
fmt.Println...