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?
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.