Skip to content

Instantly share code, notes, and snippets.

@pbdeuchler
Created July 16, 2013 02:24
Show Gist options
  • Save pbdeuchler/6005282 to your computer and use it in GitHub Desktop.
Save pbdeuchler/6005282 to your computer and use it in GitHub Desktop.
Proof of concept Go map function
package main
import (
"fmt"
"strconv"
"reflect"
)
type mapFunc func(interface{}) (interface{})
func main() {
arrayIn := []int{1, 2, 3, 4, 5}
arrayOut1 := goMap(arrayIn, intStringConversion)
for x := range(arrayOut1) {
fmt.Println(reflect.TypeOf(arrayOut1[x]))
}
fmt.Println("-------------")
arrayOut2 := goMap(arrayIn, adderFunc)
for x := range(arrayOut2) {
fmt.Println(arrayOut2[x])
}
}
func adderFunc(x interface{}) interface{} {
return x.(int) + 100
}
func intStringConversion(x interface{}) interface{} {
return strconv.Itoa(x.(int))
}
func goMap(input interface{}, function mapFunc) []interface{} {
derp := reflect.ValueOf(input) //Getting messy
var output = make([]interface{}, derp.Len())
for i := 0; i < derp.Len(); i++ {
output[i] = function(derp.Index(i).Interface())
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment