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

报告相同问题?