Initialize nested struct definition

后端 未结 3 850
天命终不由人
天命终不由人 2020-11-27 14:58

How do you initialize the following struct?

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


        
相关标签:
3条回答
  • 2020-11-27 15:40
    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",
    }
    
    0 讨论(0)
  • 2020-11-27 15:41

    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.

    0 讨论(0)
  • 2020-11-27 15:46

    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.

    0 讨论(0)
提交回复
热议问题