如何在golang中实现虚函数?我试过这个,但我不能打印“B”
type A struct {
}
type B struct {
A
}
func (self A) myVirtualFunction() {
fmt.Println("A again :(")
}
func (self A) f() {
self.myVirtualFunction()
}
func (self B) myVirtualFunction(){
fmt.Println("B :)")
}
func main() {
var b *B = new(B)
b.f()
}
答案 0 :(得分:1)
使用Golang接口方法代替C ++(纯)虚函数:
对于The Go Way来说,看看包裹排序:
>>>
{'[1, 2, 3]': 2, '[1, -2, 3]': 1, '[2, 1, 3]': 2}
{'[1, 2, 3]': 4, '[2, 1, 3]': 1, '[0, 2, 3]': 1}
>>>
和示例(按年龄自定义排序):
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}