Skip to content

Instantly share code, notes, and snippets.

@17twenty
Created August 25, 2017 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 17twenty/7a9fe72669d34e0fdf150098804e54c5 to your computer and use it in GitHub Desktop.
Save 17twenty/7a9fe72669d34e0fdf150098804e54c5 to your computer and use it in GitHub Desktop.
Building things from names using reflect and Golang
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