Initialize nested struct definition

StructGoInitialization

Struct Problem Overview


How do you initialize the following struct?

type Sender struct {
    BankCode string
    Name     string
    Contact  struct {
        Name    string
        Phone   string
    }
}

I tried:

s := &Sender{
        BankCode: "BC",
        Name:     "NAME",
        Contact {
            Name: "NAME",
            Phone: "PHONE",
        },
    }

Didn't work:

mixture of field:value and value initializers
undefined: Contact

I tried:

s := &Sender{
        BankCode: "BC",
        Name:     "NAME",
        Contact: Contact {
            Name: "NAME",
            Phone: "PHONE",
        },
    }

Didn't work:

undefined: Contact

Struct Solutions


Solution 1 - Struct

Your Contact is a field with anonymous struct type. As such, you have to repeat the type definition:

s := &Sender{
	BankCode: "BC",
	Name:     "NAME",
	Contact: struct {
		Name  string
		Phone string
	}{
		Name:  "NAME",
		Phone: "PHONE",
	},
}

But in most cases it's better to define a separate type as rob74 proposed.

Solution 2 - Struct

How about defining the two structs separately and then embedding "Contact" in "Sender"?

type Sender struct {
	BankCode string
	Name     string
	Contact
}

type Contact struct {
	Name  string
	Phone string
}

if you do it this way, your second initialization attempt would work. Additionally, you could use "Contact" on its own.

If you really want to use the nested struct, you can use Ainar-G's answer, but this version isn't pretty (and it gets even uglier if the structs are deeply nested, as shown here), so I wouldn't do that if it can be avoided.

Solution 3 - Struct

type NameType struct {
    First string
    Last  string
}
type UserType struct {
	NameType
    Username string
}

user := UserType{NameType{"Eduardo", "Nunes"}, "esnunes"}

// or

user := UserType{
	NameType: NameType{
		First: "Eduardo",
		Last:  "Nunes",
	},
	Username: "esnunes",
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKirilView Question on Stackoverflow
Solution 1 - StructAinar-GView Answer on Stackoverflow
Solution 2 - Structrob74View Answer on Stackoverflow
Solution 3 - StructEduardo NunesView Answer on Stackoverflow