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)
}
You can add a pointer to the parent in the child struct
type child struct {
Name string
parent *parent
}
func (p *child) Yell() {
fmt.Println("Child's yelling")
p.parent.Remember(p.Name + " called")
p.parent.Yell()
}
I am just a starter of Golang.
Seems Golang convention is CamelCase for class name, and when inherit a base class ("Parent") shouldn't assign a variable name. p.Parent
will automatically work, i.e. as follows:
type Child struct {
*Parent // put at top
Name string
}
func (p *Child) Yell() {
fmt.Println("Child's yelling")
p.Parent.Remember(p.Name + " called")
p.Parent.Yell()
}
Reference:
Some other example inherit with non-pointer Parent like:
type Child struct {
Parent // put at top
Name string
}
Not sure which one is more official and handy yet