Skip to content

Instantly share code, notes, and snippets.

@reusee
Created October 29, 2013 10:01

Revisions

  1. reusee created this gist Oct 29, 2013.
    33 changes: 33 additions & 0 deletions reflect.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    package main

    import (
    "fmt"
    "reflect"
    "strings"
    )

    func main() {
    l := []string{"foo", "bar", "baz"}
    ll := Map(l, func(s string) string {
    return strings.ToUpper(s)
    }).([]string)
    fmt.Printf("%v\n", ll)

    il := []int{1, 2, 3}
    ill := Map(il, func(i int) int {
    return i * 2
    }).([]int)
    fmt.Printf("%v\n", ill)
    }

    func Map(l interface{}, f interface{}) interface{} {
    lValue := reflect.ValueOf(l)
    fValue := reflect.ValueOf(f)
    retType := reflect.TypeOf(f).Out(0)
    retSlice := reflect.MakeSlice(reflect.SliceOf(retType), lValue.Len(), lValue.Len())
    for i := 0; i < lValue.Len(); i++ {
    retValue := fValue.Call([]reflect.Value{lValue.Index(i)})
    retSlice.Index(i).Set(retValue[0])
    }
    return retSlice.Interface()
    }