我想实现这样的代码,其中B继承自A并只覆盖A的Foo()方法,我希望代码打印B.Foo(),但它仍然打印A.Foo(),似乎Golang中的接收器在C++中不能像这样工作,在C++中,当启用动态绑定时,代码可以像我想要的那样工作。
我还发布了另一段代码,它可以工作,但它太难实现了,而且更像是一种黑客方式,我认为它不是Golang风格。
stdout
package main
import (
"fmt"
)
type A struct {
}
func (a *A) Foo() {
fmt.Println("A.Foo()")
}
func (a *A) Bar() {
a.Foo()
}
type B struct {
A
}
func (b *B) Foo() {
fmt.Println("B.Foo()")
}
func main() {
b := B{A: A{}}
b.Bar()
}
output: A.Foo()
下面的代码行得通,但在写的时候
a := A{}
a.Bar()
您将遇到编译器错误
package main
import (
"fmt"
)
type I interface {
Foo()
}
type A struct {
i I
}
func (a *A) Foo() {
fmt.Println("A.Foo()")
}
func (a *A) Bar() {
a.i.Foo()
}
type B struct {
A
}
func (b *B) Foo() {
fmt.Println("B.Foo()")
}
func main() {
b := B{A: A{}}
b.i = &b // here i works like an attribute of b
b.Bar()
output: B.Foo()