Home > Software design >  How to initialize an array of anonymous struct with generic field
How to initialize an array of anonymous struct with generic field

Time:03-21

I'd to learn whether it's possible to initialize an array of anonymous struct contains generic-field. Code below doesn't compile, moreover I couldn't find any sample related to:

    testCases := type [K comparable, T Numeric] []struct   {
        name     string
        args     map[K]T
        expected int
    }{
        // items ...
        {"integer", map[string]int{ "a":1 },
    }

Without anonymous structs it's easy, but not the aimed:

    type args[K comparable, T Numeric] struct {
        m map[K]T
    }
    testCases := []struct {
        name     string
        args     args[string, int]
        expected int
    }{}

Thanks!

CodePudding user response:

Type parameters are introduced so when you instantiate the type, you can give concrete types to type parameters. Given that, there is no sense in what you want to do. You want to create a generic anonymous type and instantiate it right away. You can't use this anonymous struct elsewhere (because it's anonymous), so leave out the type parameters and use the concrete types you'd instantiate the type parameters with if it would be a named type.

And to answer your original question: no, you cannot do this. The syntax does not allow this. There was a proposal to support this but was rejected: proposal: spec: generics: Anonymous generic aggregate types #45591. The workaround is to use a named struct type instead of the anonymous struct type, just as you suggested.

  • Related