From the example below, is there anyway that Child object can call Parent's method? For instance, I want Child (boy1 and girl1) to call parent's "Remember" method; so parents can remember what Child want them to remember.
Thank you so much
package main
import "fmt"
type child struct {
Name string
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
}
type parent struct {
Name string
Children []child
Memory []string
}
func (p *parent) Yell() {
fmt.Println("Parent's yelling")
}
func (p *parent) Remember(line string) {
p.Memory = append(p.Memory, line)
}
func main() {
p := parent{}
p.Name = "Jon"
boy1 := child{}
boy1.Name = "Jon's boy"
girl1 := child{}
girl1.Name = "Jon's girl"
p.Children = append(p.Children, boy1)
p.Children = append(p.Children, girl1)
fmt.Println(p)
p.Yell()
for i:=0;i<len(p.Children);i++ {
p.Children[i].Yell()
}
}
Thanks to @Jim, here's the solution. The pointer is always confusing.
package main
import "fmt"
type child struct {
Name string
prnt *parent
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
}
type parent struct {
Name string
Children []child
Memory []string
}
func (p *parent) Yell() {
fmt.Println("Parent's yelling")
}
func (p *parent) Remember(line string) {
p.Memory = append(p.Memory, line)
}
func main() {
p := parent{}
p.Name = "Jon"
boy1 := child{}
boy1.Name = "Jon's boy"
boy1.prnt = &p
girl1 := child{}
girl1.Name = "Jon's girl"
girl1.prnt = &p
p.Children = append(p.Children, boy1)
p.Children = append(p.Children, girl1)
fmt.Println(p)
p.Yell()
for i := 0; i < len(p.Children); i++ {
p.Children[i].Yell()
p.Children[i].prnt.Remember("test:" + p.Children[i].Name)
}
fmt.Println(p.Memory)
}