Go中的方法重写 [英] Method overriding in Go

查看:91
本文介绍了Go中的方法重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下代码:

type A struct {
}

func (a *A) Func1(i int) {
    a.Func2(i)
}

func (a *A) Func2(i int) {
    fmt.Println(i)
}

type B struct {
    *A
}

func (b *B) Func2(i int) {
    i += 1
    b.A.Func2(i)
}

func main() {
    var b = B{}
    b.Func1(1)
}

我有一个结构 A ,在 A 中有2个函数 Func1 Func2 ,函数A.Func1 将调用 A.Func2 .

I have a struct A, and 2 functions Func1, Func2 in A, function A.Func1 will call A.Func2.

我还有另一个嵌入结构 A 的结构 B ,还有一个覆盖了 A.Func2 的函数 Func2 .代码>.

And I have another struct B that embedding struct A, and have a function Func2 that overriding A.Func2.

当我声明值 B {} b 并调用 b.Func1(1)时,它将运行 A.Func1 并调用 A.Func2 ,但不运行 A.Func1 并调用我覆盖 A的 B.Func2 .Func2 B 中.

When I declare b that has value B{} and call b.Func1(1), it will run A.Func1 and call A.Func2 but not run A.Func1 and call B.Func2 that I override A.Func2 in B.

我的问题是我该如何修复代码,以便当我调用 b.Func1(1)时,它将运行 A.Func1 并调用 B.Func2 我覆盖了 B 中的 A.Func2 .

My question is how can I fix the code so that when I call b.Func1(1), it will run A.Func1 and call B.Func2 that I override A.Func2 in B.

推荐答案

您正在使用 b 接收方 bAFunc2调用升级方法 a.Func2(i)(i)类型.因此,实际上它是使用接收方 A 调用该函数.由于没有方法可以覆盖.只有嵌入式类型.因此,如果要使用功能,则必须创建相同功能的版本.喜欢

You are calling promoted method a.Func2(i) using b receiver b.A.Func2(i) type. So in actual it is calling the function with receiver A. Since there is no method overriding in go. Only there are embedded types . So you have to create your version of the same function if you wants your function to be used. Like

func (a *B) Func(i int){
    fmt.Println("Calling function from b receiver")
}

可以在 B Func2

func (b *B) Func2(i int) {
    i += 1
    b.Func(i)
}

检查此问题以获取更多详细信息

Check this question for more details

这篇关于Go中的方法重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆