英文:
Initialize nested struct definition
问题
你好!以下是对结构体进行初始化的正确方式:
s := &Sender{
BankCode: "BC",
Name: "NAME",
Contact: struct {
Name string
Phone string
}{
Name: "NAME",
Phone: "PHONE",
},
}
希望对你有帮助!如果你还有其他问题,请随时提问。
英文:
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
答案1
得分: 107
你的Contact
是一个带有匿名结构类型的字段。因此,你需要重复定义该类型:
s := &Sender{
BankCode: "BC",
Name: "NAME",
Contact: struct {
Name string
Phone string
}{
Name: "NAME",
Phone: "PHONE",
},
}
但在大多数情况下,像rob74建议的那样定义一个单独的类型会更好。
英文:
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
得分: 37
如何先分别定义这两个结构体,然后在"Sender"中嵌入"Contact"呢?
type Sender struct {
BankCode string
Name string
Contact // 嵌入"Contact"
}
type Contact struct {
Name string
Phone string
}
如果按照这种方式进行定义,你的第二次初始化尝试将会成功。此外,你还可以单独使用"Contact"。
如果你真的想使用嵌套结构体,你可以使用Ainar-G的答案,但这种方式不太美观(如果结构体嵌套层级很深,就会变得更加丑陋,可以在这里看到示例),所以如果可以避免的话,我不会推荐这样做。
英文:
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.
答案3
得分: 1
以下是代码的中文翻译:
type NameType struct {
First string
Last string
}
type UserType struct {
NameType
Username string
}
user := UserType{NameType{"Eduardo", "Nunes"}, "esnunes"}
// 或者
user := UserType{
NameType: NameType{
First: "Eduardo",
Last: "Nunes",
},
Username: "esnunes",
}
希望对你有帮助!
英文:
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",
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论