给父级 Golang 结构字段赋值

huangapple go评论108阅读模式
英文:

Assign value to parent golang structure field

问题

有两种情况:

第一种情况:

  1. type A struct {
  2. A_FIELD string
  3. }
  4. type B struct {
  5. A
  6. B_FIELD string
  7. }
  8. func main() {
  9. b := &B{
  10. A_FIELD: "aaaa_field",
  11. B_FIELD: "bbbb_field",
  12. }
  13. }

第二种情况:

  1. type A struct {
  2. A_FIELD string
  3. }
  4. type B struct {
  5. A
  6. B_FIELD string
  7. }
  8. func main() {
  9. b := &B{}
  10. b.A_FIELD = "aaaa_field"
  11. b.B_FIELD = "bbbb_field"
  12. fmt.Printf("Good!")
  13. }

为什么第二种情况可以正常工作,而第一种情况不行?我收到了编译时异常。我应该如何修改第一种情况使其正常工作?

英文:

There are two situations:

  1. type A struct {
  2. A_FIELD string
  3. }
  4. type B struct {
  5. A
  6. B_FIELD string
  7. }
  8. func main() {
  9. b := &B{
  10. A_FIELD: "aaaa_field",
  11. B_FIELD: "bbbb_field",
  12. }
  13. }

And

  1. type A struct {
  2. A_FIELD string
  3. }
  4. type B struct {
  5. A
  6. B_FIELD string
  7. }
  8. func main() {
  9. b := &B{}
  10. b.A_FIELD = "aaaa_field"
  11. b.B_FIELD = "bbbb_field"
  12. fmt.Printf("Good!")
  13. }

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

为什么第二个能够工作,而第一个不能工作?

因为

  1. b.A_FIELD = "aaaa_field"

实际上是

  1. b.A.A_FIELD = "aaaa_field"

的伪装。

我应该如何修改第一个才能使其工作?

  1. func main() {
  2. b := &B{
  3. A: A{
  4. A_FIELD: "aaaa_field",
  5. },
  6. B_FIELD: "bbbb_field",
  7. }
  8. }

你应该阅读《Effective Go》中的嵌入的工作原理

英文:

> Why the second one is working, but the first one is not?

Because

  1. b.A_FIELD = "aaaa_field"

is actually

  1. b.A.A_FIELD = "aaaa_field"

in disguise.

> How should I change first one to work?

  1. func main() {
  2. b := &B{
  3. A: A{
  4. A_FIELD: "aaaa_field",
  5. },
  6. B_FIELD: "bbbb_field",
  7. }
  8. }

You should read how embedding work on Effective Go.

huangapple
  • 本文由 发表于 2015年6月19日 20:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/30937810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定