Initialize nested struct definition

后端 未结 3 856
天命终不由人
天命终不由人 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: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.

提交回复
热议问题