Created
April 2, 2016 09:58
-
-
Save monkseal/a0d2a7fad631b5414f7214c55bbd782f to your computer and use it in GitHub Desktop.
Broken golang collect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
// NOTE: will not work because golang does not allow | |
// overloading. This was done for performance reasons. | |
// see https://golang.org/doc/faq#overloading | |
func Collect(list []car, f func(car) int) []int { | |
result := make([]int, 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)) | |
getYear := func(c car) int { | |
return c.year | |
} | |
fmt.Println(Collect(cars, getYear)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment