dtcaw02086
2014-11-11 14:13
浏览 614
已采纳

在Golang中初始化嵌套的结构体定义

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
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doubanduo7620 2014-11-11 14:26
    已采纳

    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.

    点赞 评论
  • duanhe4155 2014-11-11 14:21

    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.

    点赞 评论
  • dongpaozhi5734 2015-01-16 22:21
    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",
    }
    
    点赞 评论

相关推荐 更多相似问题