小编典典

初始化嵌套结构定义

go

您如何初始化以下结构?

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

我试过了:

s := &Sender{
        BankCode: "BC",
        Name:     "NAME",
        Contact {
            Name: "NAME",
            Phone: "PHONE",
        },
    }

没用:

mixture of field:value and value initializers
undefined: Contact

我试过了:

s := &Sender{
        BankCode: "BC",
        Name:     "NAME",
        Contact: Contact {
            Name: "NAME",
            Phone: "PHONE",
        },
    }

没用:

undefined: Contact

阅读 349

收藏
2020-07-02

共1个答案

小编典典

Contact是一个具有匿名结构类型的字段。因此,您必须重复类型定义:

s := &Sender{
    BankCode: "BC",
    Name:     "NAME",
    Contact: struct {
        Name  string
        Phone string
    }{
        Name:  "NAME",
        Phone: "PHONE",
    },
}

但在大多数情况下,最好将其定义为rob74建议的单独类型。

2020-07-02