New instance of struct from the type at runtime in

2019-08-09 01:24发布

问题:

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?

回答1:

i reviewed your code. when you new a type with reflect, you got a value in Value type, need to call Interface() to get the interface of that new generated value

check the code http://play.golang.org/p/CHWSV8EG7D



回答2:

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{}.

//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()//<--wrong
    fmt.Println(reflect.TypeOf(db.Template), ret)
    decoder.Decode(ret)
    return ret.Interface()
}
//print
//Hello, playground
//Value []byte: {"email":"jdoe@acme.com","name":"John Doe","_id":"142321"}
//main.UserInfo {  }
//TypeOf(ret): main.UserInfo
//ValueOf(ret): {  }
//Value: {  }

For get *sometype value use .Interface(), so you will can to decode. See:

//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]))
    retValue := reflect.New(reflect.TypeOf(db.Template))
    retInter := retValue.Interface()//<-- 
    fmt.Println(reflect.TypeOf(db.Template), retInter)
    decoder.Decode(retInter)
    return retInter
}

Result:

Hello, playground
Value []byte: {"email":"jdoe@acme.com","name":"John Doe","_id":"142321"}
main.UserInfo &{  }
TypeOf(ret): *main.UserInfo
ValueOf(ret): &{jdoe@acme.com John Doe 142321}
Value: &{jdoe@acme.com John Doe 142321}

In playground: https://play.golang.org/p/veTUho5D4d



标签: reflection go