您如何初始化以下结构?
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
您Contact是一个具有匿名结构类型的字段。因此,您必须重复类型定义:
Contact
s := &Sender{ BankCode: "BC", Name: "NAME", Contact: struct { Name string Phone string }{ Name: "NAME", Phone: "PHONE", }, }
但在大多数情况下,最好将其定义为rob74建议的单独类型。