Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.