猿问

Golang,调用父母的方法

从下面的例子来看,Child 对象是否可以调用 Parent 的方法?例如,我想让孩子(男孩 1 和女孩 1)调用父母的“记住”方法;这样父母就可以记住孩子想让他们记住的东西。


太感谢了


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()

    }

}


临摹微笑
浏览 148回答 3
3回答

月关宝盒

这是解决方案。指针总是令人困惑。包主import "fmt"type child struct {&nbsp; &nbsp; Name string&nbsp; &nbsp; prnt *parent}func (p *child) Yell() {&nbsp; &nbsp; fmt.Println("Child's yelling")}type parent struct {&nbsp; &nbsp; Name&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; Children []child&nbsp; &nbsp; Memory&nbsp; &nbsp;[]string}func (p *parent) Yell() {&nbsp; &nbsp; fmt.Println("Parent's yelling")}func (p *parent) Remember(line string) {&nbsp; &nbsp; p.Memory = append(p.Memory, line)}func main() {&nbsp; &nbsp; p := parent{}&nbsp; &nbsp; p.Name = "Jon"&nbsp; &nbsp; boy1 := child{}&nbsp; &nbsp; boy1.Name = "Jon's boy"&nbsp; &nbsp; boy1.prnt = &p&nbsp; &nbsp; girl1 := child{}&nbsp; &nbsp; girl1.Name = "Jon's girl"&nbsp; &nbsp; girl1.prnt = &p&nbsp; &nbsp; p.Children = append(p.Children, boy1)&nbsp; &nbsp; p.Children = append(p.Children, girl1)&nbsp; &nbsp; fmt.Println(p)&nbsp; &nbsp; p.Yell()&nbsp; &nbsp; for i := 0; i < len(p.Children); i++ {&nbsp; &nbsp; &nbsp; &nbsp; p.Children[i].Yell()&nbsp; &nbsp; &nbsp; &nbsp; p.Children[i].prnt.Remember("test:" + p.Children[i].Name)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(p.Memory)}

猛跑小猪

您可以在子结构中添加指向父结构的指针type child struct {&nbsp; &nbsp; Name string&nbsp; &nbsp; parent *parent}func (p *child) Yell() {&nbsp; &nbsp; fmt.Println("Child's yelling")&nbsp; &nbsp; p.parent.Remember(p.Name + " called")&nbsp; &nbsp; p.parent.Yell()}

慕姐4208626

我只是 Golang 的初学者。似乎Golang约定是类名的CamelCase,并且在继承基类(“Parent”)时不应分配变量名。 p.Parent将自动工作,即如下:type Child struct {&nbsp; &nbsp; *Parent&nbsp; &nbsp;// put at top&nbsp; &nbsp; Name string}func (p *Child) Yell() {&nbsp; &nbsp; fmt.Println("Child's yelling")&nbsp; &nbsp; p.Parent.Remember(p.Name + " called")&nbsp; &nbsp; p.Parent.Yell()}参考:http://arch-stable.blogspot.hk/2012/05/golang-call-inherited-constructor.htmlhttps://medium.com/@simplyianm/why-gos-structs-are-superior-to-class-based-inheritance-b661ba897c67其他一些示例使用非指针 Parent 继承,例如:type Child struct {&nbsp; &nbsp; Parent&nbsp; &nbsp;// put at top&nbsp; &nbsp; Name string}不确定哪一个更正式和方便
随时随地看视频慕课网APP

相关分类

Go
我要回答