dongxi7704 2019-03-14 08:00
浏览 84
已采纳

Golang中的struct通用图

I have 2 types of struct based on 3rdparties code that I cant change

type AddEvent struct {
}

type DeleteEvent struct {
}

I would like to create a map of string as key and Object as value so each time I got new event I will add it to the map I.E Map should look like this:

EventMap:
    event1,AddEvent{}
    event2,AddEvent{}
    event2,DeleteEvent{}

The issue that AddEvent and DeleteEvent are not defined as interfaces.
Is there I way to create a generic map in go using any struct as a value and in case yes, how can I read it do I need to check the type using reflect

I.E
event:=EventMap[event1]
if reflect.TypeOf(event)==AddEvent{
}else if reflect.TypeOf(event)==DeleteEvent{
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-03-14 08:15
    关注

    what comment says looks good, but missing type switch. Full version maybe you need is:

    m := make(map[string]interface{})
    addEvent := new(AddEvent)
    m["event1"] = addEvent
    switch m["event1"].(type) {
    case *AddEvent:
        // do something
    case *DeleteEvent:
        // do other things
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: