Go语言实现数组的Map函数

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

你可能感兴趣的:(map,Go,golang,go语言)