Created
July 16, 2013 02:24
-
-
Save pbdeuchler/6005282 to your computer and use it in GitHub Desktop.
Proof of concept Go map function
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" | |
"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