package main
import (
"fmt"
"reflect"
)
func Map(slice interface{}, fn func(a interface{}) interface{}) interface{} {
val := reflect.ValueOf(slice)
out := reflect.MakeSlice(reflect.TypeOf(slice), val.Len(), val.Cap())
for i := 0; i < val.Len(); i++ {
out.Index(i).Set(
reflect.ValueOf(fn(val.Index(i).Interface())),
)
}
return out.Interface()
}
func main() {
a := Map([]int{1, 2, 3, 4}, func(val interface{}) interface{} {
return val.(int) * 2
})
fmt.Printf("%T: %v\n", a, a)
}
http://play.golang.org/p/g77ofhvNyj
有疑问加站长微信联系(非本文作者)