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

在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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?