Created
October 29, 2013 10:01
-
-
Save reusee/7211833 to your computer and use it in GitHub Desktop.
reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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