I’m really confused about how the rules around generics work. I just want to have a function accept multiple custom types and have different logic for each one.
type myObjOne struct {
myfield string
}
type myObjTwo struct {
myObjTwo
myOtherField string
}
type Generic interface {
myObjOne | myObjTwo
}
func derp[T Generic](c T) {
switch any(c).(type) {
case myObjOne:
// I can't access the fields of my types like this
c.myfield = "sdfsfsdfdsf"
case myObjTwo:
c.myOtherField = "sdfsfsdfdsf"
}
return
}
Why is c.myfield throwing c.myfield undefined (type T has no field or method myfield) compilerMissingFieldOrMethod?
>Solution :
c is type T, not the result of the type assertion. Fix by assigning the result of the type assertion to a variable.
func derp[T Generic](c T) {
switch c := any(c).(type) {
case myObjOne:
// I can't access the fields of my types like this
c.myfield = "sdfsfsdfdsf"
case myObjTwo:
c.myOtherField = "sdfsfsdfdsf"
}
return
}
This code declares a second variable c in the type switch. The type of c depends on the branch of the switch.