Skip to content

Instantly share code, notes, and snippets.

@monkseal
Created April 2, 2016 09:56
Show Gist options
  • Save monkseal/13dfccb5dba775d277e6890a71702120 to your computer and use it in GitHub Desktop.
Save monkseal/13dfccb5dba775d277e6890a71702120 to your computer and use it in GitHub Desktop.
Simple Collect func for an Array or Slice of cars
package main
import "fmt"
type car struct {
make string
model string
year int
}
func Collect(list []car, f func(car) string) []string {
result := make([]string, len(list))
for i, item := range list {
result[i] = f(item)
}
return result
}
func main() {
var cars = []car{
car{make: "Subaru", model: "Outback", year: 2007},
car{make: "Saab", model: "Sonett III", year: 1973},
car{make: "Lexus", model: "SC 430", year: 2009},
car{make: "Volvo", model: "V90", year: 1992},
}
getMake := func(c car) string {
return c.make
}
fmt.Println(Collect(cars, getMake))
getModel := func(c car) string {
return c.model
}
fmt.Println(Collect(cars, getModel))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment