英文:
Assign value to parent golang structure field
问题
有两种情况:
第一种情况:
type A struct {
A_FIELD string
}
type B struct {
A
B_FIELD string
}
func main() {
b := &B{
A_FIELD: "aaaa_field",
B_FIELD: "bbbb_field",
}
}
第二种情况:
type A struct {
A_FIELD string
}
type B struct {
A
B_FIELD string
}
func main() {
b := &B{}
b.A_FIELD = "aaaa_field"
b.B_FIELD = "bbbb_field"
fmt.Printf("Good!")
}
为什么第二种情况可以正常工作,而第一种情况不行?我收到了编译时异常。我应该如何修改第一种情况使其正常工作?
英文:
There are two situations:
type A struct {
A_FIELD string
}
type B struct {
A
B_FIELD string
}
func main() {
b := &B{
A_FIELD: "aaaa_field",
B_FIELD: "bbbb_field",
}
}
And
type A struct {
A_FIELD string
}
type B struct {
A
B_FIELD string
}
func main() {
b := &B{}
b.A_FIELD = "aaaa_field"
b.B_FIELD = "bbbb_field"
fmt.Printf("Good!")
}
Why the second one is working, but the first one is not? I receive compile time exceptions. How should I change first one to work?
答案1
得分: 7
为什么第二个能够工作,而第一个不能工作?
因为
b.A_FIELD = "aaaa_field"
实际上是
b.A.A_FIELD = "aaaa_field"
的伪装。
我应该如何修改第一个才能使其工作?
func main() {
b := &B{
A: A{
A_FIELD: "aaaa_field",
},
B_FIELD: "bbbb_field",
}
}
你应该阅读《Effective Go》中的嵌入的工作原理。
英文:
> Why the second one is working, but the first one is not?
Because
b.A_FIELD = "aaaa_field"
is actually
b.A.A_FIELD = "aaaa_field"
in disguise.
> How should I change first one to work?
func main() {
b := &B{
A: A{
A_FIELD: "aaaa_field",
},
B_FIELD: "bbbb_field",
}
}
You should read how embedding work on Effective Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论