I want to write a single function that can add certain fields to Firebase message structs. There are two different types of message, Message
and MulticastMessage
, which both contain Android
and APNS
fields of the same types, but the message types don't have an explicitly declared relationship with each other.
I thought I should be able to do this:
type firebaseMessage interface {
*messaging.Message | *messaging.MulticastMessage
}
func highPriority[T firebaseMessage](message T) T {
message.Android = &messaging.AndroidConfig{...}
....
return message
}
but it gives the error message.Android undefined (type T has no field or method Android)
. And I can't write switch m := message.(type)
either (cannot use type switch on type parameter value message (variable of type T constrained by firebaseMessage)
).
I can write switch m := any(message).(type)
, but I'm still not sure whether that will do what I want.
I've found a few other SO questions from people confused by unions and type constraints, but I couldn't see any answers that helped explain why this doesn't work (perhaps because I'm trying to use it with structs instead of interfaces?) or what union type constraints are actually useful for.