douxunchen3498 2016-03-04 19:56
浏览 53
已采纳

Golang,打电话给父母的方法

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)
}
  • 写回答

2条回答 默认 最新

  • douyeyan0650 2016-03-04 20:03
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示