dimanche 21 octobre 2018

Creating instances of a struct based on a String

I've followed instructions on other posts regarding dynamically creating an instance of a struct based on a string. Original Post.

As per below when I first print the type of "v" it says its "main.MyString". I then unmarshal the json as I would normally do if I'd created an instance of MyString. However after I do this it changes to the TypeOf v to map[string]interface {} Firstly, I dont understand why this is happening?

Secondly, if I change the line to "var v MyString" then there is no problem but this doesn't allow me to create an object based on a string, any Ideas?

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type MyString struct {
    Num1 int `json:"num1"`
    Num2 int `json:"num2"`
}

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["MyString"] = reflect.TypeOf(MyString{})

}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()
    // Maybe fill in fields here if necessary
    return v.Interface()
}

func main() {

    someJson := `
    {
        "num1": 5,
        "num2": 10
    }
    `

    v := makeInstance("MyString")

    fmt.Println(reflect.TypeOf(v))

    err := json.Unmarshal([]byte(someJson), &v)

    if err != nil {

        fmt.Println("error:", err)
    }

    fmt.Println(reflect.TypeOf(v))
    fmt.Println(v)
}

Go Playground Link





Aucun commentaire:

Enregistrer un commentaire