Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created May 11, 2015 07:50
Show Gist options
  • Save montanaflynn/b03488eea65cc558a62a to your computer and use it in GitHub Desktop.
Save montanaflynn/b03488eea65cc558a62a to your computer and use it in GitHub Desktop.
GoMap
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