从下面的示例来看,无论如何,Child对象可以调用Parent的方法吗?例如,我希望孩子(boy1和girl1)打电话给父母"记住"方法;所以父母可以记住孩子想让他们记住的事。
非常感谢
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()
}
}
感谢@Jim,这是解决方案。指针总是令人困惑。
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)
}
答案 0 :(得分:2)
您可以在子结构中添加指向父级的指针
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()
}
答案 1 :(得分:1)
我只是Golang的首发。
似乎Golang约定是CamelCase的类名,当继承时,基类(“Parent”)不应该指定变量名。 p.Parent
将自动生效,即如下:
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()
}
参考:
其他一些示例使用非指针Parent继承,如:
type Child struct {
Parent // put at top
Name string
}
不确定哪一个更官方更方便