
type Parent struct{} func (p *Parent) A() { p.B() } func (p *Parent) B() { fmt.Println("parent.B()") } type Child struct { Parent } func (c *Child) B() { fmt.Println("child.B()") } 定义了两个结构体,Parent 和 Child
Parent 有 A()和 B()两个方法,在 A 中调用了 B
Child 只实现了 B(),然后按如下方式调用:
func main() { p := &Parent{} c := &Child{ p.A() c.A() c.Parent.A() } 发现 c.A()和 c.Parent.A()都只调用到了 Parent 的 B()方法
有办法可以在 A()方法中调用到 Child 的 B()方法吗
1 Kilerd May 2, 2017 via iPhone 不可能吧?! |
2 shadowind May 2, 2017 go 的嵌套不会重载,所以都是`Parent`的`B()`方法。 使用`interface`可以解决你的需求。 |
3 x8 May 2, 2017 加一个方法 func (c *Child) A() { c.B() } 调什么方法得看方法绑定的指针类型 |
4 sumhat May 2, 2017 Golang 中 Parent 不知道 Child 的存在,一旦调用了 Parent 的方法,之后所有的调用都局限在 Parent 中。 |
5 bianhua May 2, 2017 @sumhat 其实可以解释的更简单一点:Golang 没有 Override。之所以 c.A()能运行,仅仅是因为这是一种语法糖。实际上 c.A()跟 c.Parent.A()是等价的。 |
6 rrfeng May 2, 2017 楼上已经回答的很清楚了。 你需要 interface |
7 zhujinliang May 2, 2017 还有种方法 package main import "fmt" type CanB interface { B() } type Parent struct { instance CanB } func (p *Parent) A() { p.B() } func (p *Parent) B() { if p.instance != nil { p.instance.B() return } fmt.Println("parent.B()") } func (p *Parent) SetInstance(i interface{}) { if inst, ok := i.(CanB); ok { p.instance = inst } } type Child struct { Parent } func (c *Child) B() { fmt.Println("child.B()") } func main() { p := &Parent{} c := &Child{} c.SetInstance(c) p.A() c.A() c.Parent.A() } |
8 zhujinliang May 2, 2017 |
9 Immortal May 2, 2017 重载 Child 的 A 方法 chlid.A()会调用到 child 的 A 方法 child.parent.A()会调用到 parent 的 A 方法 |
10 jarlyyn May 2, 2017 个人觉得,go 没有 oop …… 所谓的继承其实就是帮你自动调用嵌入结构的同名函数的语法糖。 就我的角度来看,大部分的操作 需要一个外部函数 调用 interface 来处理。 而非写作方法本身。 也就是 不是 p.A(),c.A() 而是 A(p),A(c) |
11 scnace May 2, 2017 2L 正解 贴下实现,顺便贴下实现(不是很喜欢这么写),https://play.golang.org/p/6NcQ45ai8v |
12 scnace May 2, 2017 |
14 hilow May 2, 2017 @zhujinliang 厉害了 |
15 croz OP 学习了楼上给出的方法,非常感谢 |