Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use generics with custom types?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading