gpt4 book ai didi

去虚函数模拟

转载 作者:IT王子 更新时间:2023-10-29 01:52:40 26 4
gpt4 key购买 nike

在 go 中是否存在一些实现虚函数行为的技巧?我有以下示例。

package main

import "fmt"

type A struct {
}

type B struct {
*A
}

func (this *A) Do() {
fmt.Println("IM DO")
this.DoVirtual()
}

func (this *A) DoVirtual() {
fmt.Println("IM DoVirtual Default implementation")
}

func (this *B) DoVirtual() {
fmt.Println("IM DoVirtual B implementation")
}

func main() {
a := &A{}
a.Do()
fmt.Println("----")
b := &B{}
b.DoVirtual()
b.Do() // How to make here B.DoVirtual call
}

最后一个 Do() 调用也使用默认的 DoVirtual 实现,但实际上这不是我想要的。 go lang iheritance model 是这样的原因:this *B 和 this *A 在这种情况下是不同的指针,但我想知道是否有可能对这种行为进行一些模拟,最后一次调用中的 DoVirtual 将从 B 类中使用.

最佳答案

当编译器选择 func (this *A) Do() { 时,封闭的 B 已经消失,不再可访问。 Go 不支持 is-a 结构,只支持 has-a(组合)。如果实现一个 func (this *B) Do() { 它将取代 *A 上的 Do()。当然,这并不是您真正想要的。

我认为实现和动机的最佳解释在这里Less is exponentially more来自 Rob Pike。

关于去虚函数模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36884609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com