Created
May 11, 2015 07:50
-
-
Save montanaflynn/b03488eea65cc558a62a to your computer and use it in GitHub Desktop.
GoMap
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" | |
) | |
type mapf func(interface{}) interface{} | |
func Map(in interface{}, fn mapf) interface{} { | |
val := reflect.ValueOf(in) | |
out := make([]interface{}, val.Len()) | |
for i := 0; i < val.Len(); i++ { | |
out[i] = fn(val.Index(i).Interface()) | |
} | |
return out | |
} | |
func main() { | |
a := []int{1, 2, 3, 4} | |
b := Map(a, func(val interface{}) interface{} { | |
return val.(int) * 2 | |
}) | |
fmt.Printf("Mapped %v to %v\n", a, b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment