use*_*847 0 inheritance overriding go
澄清:我刚刚学习 GO,遇到了这个问题。
我正在尝试实现一个继承一个方法的“类”,该方法调用应该由子类实现的“虚拟”方法。这是我的代码:
package main
import (
"fmt"
"sync"
)
type Parent struct {
sync.Mutex
MyInterface
}
func (p *Parent) Foo() {
p.Lock()
defer p.Unlock()
p.Bar()
}
func (p *Parent) B(){
panic("NOT IMPLEMENTED")
}
func (p *Parent) A() {
p.Lock()
defer p.Unlock()
p.B()
}
type MyInterface interface {
Foo()
Bar()
}
type Child struct {
Parent
Name string
}
func (c *Child) Bar(){
fmt.Println(c.Name)
}
func (c *Child) B(){
fmt.Println(c.Name)
}
func main() {
c := new(Child)
c.Name = "Child"
// c.A() panic
c.Foo() // pointer error
}
我遗漏了一些关于对 Child 的值进行异步更新的 sync.Mutex 的代码。
所以显然在 A() 或 Foo() 中,指针 p 的类型为 Parent。我应该如何更改我的代码,以便 A/Foo 引用 Child 类中定义的 B/Bar?