I am trying to create new instance of a struct, using it's type (reflect.TypeOf) at runtime. I have followed this thread on StackOverflow How do you create a new instance of a struct from it's Type at runtime in Go?. Here is my implementation (also at http://play.golang.org/p/BtX0d5Ytu8):
package main
import (
"fmt"
"reflect"
"encoding/json"
"bytes"
)
type UserInfo struct {
Email string `json:"email"`
FullName string `json:"name"`
ID string `json:"_id"`
}
func main() {
fmt.Println("Hello, playground")
db := DBEngine{}
db.DB = make(map[string][]byte)
db.Register(UserInfo{})
db.Put("142321", UserInfo{"jdoe@acme.com", "John Doe", "142321"})
ret := db.Get("142321")
fmt.Println("TypeOf(ret):", reflect.TypeOf(ret))
fmt.Println("ValueOf(ret):", reflect.ValueOf(ret))
fmt.Println("Value:", ret)
}
type DBEngine struct {
Template interface{}
DB map[string][]byte
}
func (db *DBEngine) Register(v interface{}) {
db.Template = v
}
//Set User defined object
func (db *DBEngine) Put(key string, v interface{}) {
res, _ := json.Marshal(v)
db.DB[key] = res
}
//Return user defined object
func (db *DBEngine) Get(key string) interface{} {
decoder := json.NewDecoder(bytes.NewReader(db.DB[key]));
fmt.Println("Value []byte:", string(db.DB[key]))
ret := reflect.New(reflect.TypeOf(db.Template)).Elem()
fmt.Println(reflect.TypeOf(db.Template), ret)
decoder.Decode(ret)
return ret.Interface()
}
For some reason, I always get empty struct. I am unable to set fields or modify. Can someone suggest what is wrong?
On run reflect.New(sometype) result in an pointer for reflect.Value of sometype. If you use .Elem() will get direct value for reflect.Value that is empty. For this main.UserInfo{}.
For get *sometype value use .Interface(), so you will can to decode. See:
Result:
In playground: https://play.golang.org/p/veTUho5D4d
i reviewed your code. when you new a type with reflect, you got a value in
Value
type, need to callInterface()
to get the interface of that new generated valuecheck the code http://play.golang.org/p/CHWSV8EG7D