Answer the question
In order to leave comments, you need to log in
Embedded struct initialization?
Hello!
I'll give the code right away, then the analysis:
package main
import "fmt"
type Parent struct {
foo int
}
type Child struct {
Parent
bar int
}
func main() {
var parent = &Parent{ foo: 12 }
var child = &Child{ parent, bar: 111 }
child.Parent.foo++
fmt.Println(parent.foo) // parent.foo should be 13
}
C:\Windows\system32\cmd.exe /c (go run test1.go ^& pause)
# command-line-arguments
.\test1.go:18: mixture of field:value and value initializers
Для продолжения нажмите любую клавишу . . .
Answer the question
In order to leave comments, you need to log in
It looks like I found a solution, but I'm not sure if it's correct, the code is:
package main
import "fmt"
type Parent struct {
foo int
}
type Child struct {
Parent *Parent
bar int
}
func main() {
var parent = &Parent{ foo: 12 }
var child = &Child{ Parent: *&parent, bar: 111 }
child.Parent.foo++
fmt.Println(&parent.foo, &child.Parent.foo)
fmt.Println(child.Parent.foo, parent.foo)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question