Home > Software design >  anonymous nested struct usage
anonymous nested struct usage

Time:10-06

I've asked this question before and deleted it. but I don't understand. I tried everything but still getting error. how can i use this struct. or am i doing it wrong

type Unit struct{
    category struct{
        name string
    }
}

CodePudding user response:

Doing the following:

var unit = Unit{
    category: {
        name: "foo",
    },
}

will NOT work because the language specification says that you MUST specify the type when initializing a struct's field with a composite literal value. E.g. a nested struct, or a map, or a slice, etc.


Since category's type is an unnamed composite type, to initialize the field you MUST repeat the unnamed composite type's definition.

type Unit struct{
    category struct{
        name string
    }
}

var unit = Unit{
    category: struct{
        name string
    }{
        name: "foo",
    },
}

Alternative, do not use anonymous structs.

type Category struct {
    name string
}

type Unit struct{
    category Category
}

var unit = Unit{
    category: Category{
        name: "foo",
    },
}

And if you want to use this struct outside of the package in which it is declared you MUST export its fields

type Category struct {
    Name string
}

type Unit struct{
    Category Category
}

// ...

var unit = mypkg.Unit{
    Category: mypkg.Category{
        Name: "foo",
    },
}
  •  Tags:  
  • go
  • Related