Created
August 25, 2017 01:57
-
-
Save 17twenty/7a9fe72669d34e0fdf150098804e54c5 to your computer and use it in GitHub Desktop.
Building things from names using reflect and Golang
This file contains 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 ( | |
"log" | |
"reflect" | |
) | |
var objectMap = make(map[string]reflect.Type) | |
type MyString struct { | |
} | |
type Foo string | |
func init() { | |
// Lazy hack but you walk the AST and build this ... if you wanted to | |
myVec := []interface{}{ | |
MyString{}, | |
Foo(""), | |
0, | |
0.0, | |
} | |
for i := range myVec { | |
objectMap[reflect.TypeOf(myVec[i]).String()] = reflect.TypeOf(myVec[i]) | |
log.Println("Added", objectMap[reflect.TypeOf(myVec[i]).String()]) | |
} | |
} | |
func CreateFromName(name string) (interface{}, bool) { | |
if val, ok := objectMap[name]; ok { | |
return reflect.New(val).Elem().Interface(), true | |
} | |
return nil, false | |
} | |
func main() { | |
ms, ok := CreateFromName("main.Foo") | |
if !ok { | |
log.Println("Not OK :(") | |
} | |
log.Println(reflect.TypeOf(ms), ms) | |
ms = Foo("Yay") | |
log.Println(reflect.TypeOf(ms), ms) | |
// Try a builtin | |
builtin, ok := CreateFromName("int") | |
if !ok { | |
log.Println("Not OK :(") | |
} | |
log.Println(reflect.TypeOf(builtin), builtin) | |
builtin = 10 | |
log.Println(reflect.TypeOf(builtin), builtin) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment