给父级 Golang 结构字段赋值

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

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.

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:

确定