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 can i use golang nested struct i tried everything but i get error?

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

>Solution :

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

Doing the following:

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

will not work because the language specification says that you MUST provide the type when initializing a struct literal’s field using a composite literal value for that field.


category‘s type is an anonymous struct, because of that you need to repeat the whole type when trying to initialize it.

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",
    },
}
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