Reputation: 683
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{
}
Upvotes: 1
Views: 2166
Reputation: 419
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
}
Upvotes: 5