dimanche 21 octobre 2018

Creating objects dynamically based on a string

I'm trying to dynamically create structs based on a string.

In the below example reflect.TypeOf &c and &c1 are different because I return interface{} from makeInstance. TypeOf c and c1 are the same.

My question is how do I change the way I handle the output of makeInstance so it creates an object identical to c1 but will still allow me to create objects identical to b1 also?

type Car struct {
    Make  int `json:"make"`
    Model int `json:"model"`
}

type Bus struct {
    Seats int `json:"seats"`
    Route int `json:"route"`
}

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

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

}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()

    return v.Interface()
}

func main() {

    c := makeInstance("Car")
    b := makeInstance("Bus")

    var b1 Bus
    var c1 Car

    fmt.Println(reflect.TypeOf(&c))
    fmt.Println(reflect.TypeOf(&c1))
    fmt.Println(reflect.TypeOf(c))  
    fmt.Println(reflect.TypeOf(c1))

Let me know if I'm not asking this in the correct way.





Aucun commentaire:

Enregistrer un commentaire