70

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
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Kiril
  • 6,009
  • 13
  • 57
  • 77

3 Answers3

107

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
  • 2
    Ok, that seems to be the right answer, but as you say rob74's answer is more elegant. – Kiril Nov 11 '14 at 14:27
37

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.

rob74
  • 4,939
  • 29
  • 31
  • This is another option, but I just want to know how to initialize a nested struct. – Kiril Nov 11 '14 at 14:26
  • 1
    Your answer is a better way to solve nested struct definition, but Ainar-G's answer is the correct one for my question. – Kiril Nov 11 '14 at 14:49
1
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",
}