我决定既然泛型已经被引入到 Go 中,那么类似的东西map/reduce应该是可能的。所以,我天真地尝试了一下,我得到了错误: ./prog.go:18:36: cannot use thing (variable of type int) as type I in argument to mapper
这并不能解释问题是否是根本性的,或者我只是在语法上做错了什么。通用 map/reduce 可以在 Go 中实现吗?
package main
import "fmt"
func main() {
things := []int{1, 2, 3, 4}
results := Map(things, func(t int) int {
return t + 1
})
fmt.Printf("%v", results)
}
func Map[I interface{}, O interface{}](things []I, mapper func(thing I) O) []O {
results := make([]O, 0, len(things))
for thing := range things {
results = append(results, mapper(thing))
}
return results
}
青春有我
守候你守候我
相关分类