Skip to content

Instantly share code, notes, and snippets.

@reusee
Created October 29, 2013 10:01
Show Gist options
  • Save reusee/7211833 to your computer and use it in GitHub Desktop.
Save reusee/7211833 to your computer and use it in GitHub Desktop.
reflection
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment