dongtuo5611 2018-10-22 06:26
浏览 47
已采纳

根据字符串动态创建对象

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))

Edit:

My overall outcome is to have a program that reads a json config file that will list the types of objects I want to go off and hit a rest api and collect e.g.

{
    "auth":[{
                "username": "admin",
                "password": "admin"
            }],
    "transport":[
            {
                "vehicle":["car", "bus"]
            }]
}

When looping through vehicle it would hit an api and perform a query and return data. I would then want to create an array of the which ever vehicle is included in the config and unmarshal the json response into it. I'm trying to create the objects dynamically so I could avoid having to check if vehicle = car, if vehicle = bus etc as I will eventually have many types of vehicles but may not always have every vehicle and it seems long winded.

  • 写回答

2条回答 默认 最新

  • doujiyan0031 2018-10-22 07:09
    关注

    The function returns values of type Car and Bus as written. If you want the variable in main to have a specific type, then use a type assertion:

    c := makeInstance("Car").(Car)
    

    If your goal is to get a pointer to values of these types, then return the pointer from makeInstance:

    func makeInstance(name string) interface{} {
        return reflect.New(typeRegistry[name]).Interface()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集