【问题标题】:Executing actual object method from inherited struct without cast type to inherited type从没有强制转换类型的继承结构执行实际对象方法到继承类型
【发布时间】:2018-11-30 03:15:50
【问题描述】:
package main

import (
    "fmt"
)

type IA interface {
    Parse()
    Name() string
}

type A struct {
    IA
}

func (a *A) Name() string {
    return "AName"
}

func (a *A) Parse() {
    fmt.Println("A-" + a.Name())
}

type B struct {
    A
}

func (b *B) Name() string {
    return "BName"
}


func main() {
    a := &A{}
    b := &B{}

    a.Parse()
    b.Parse() // I would like to see "A-BName"
}

Playground

当我从继承的结构中执行方法并在其中执行另一个结构方法时 - 是从继承的结构中执行的方法,而不是实际的对象类型。

【问题讨论】:

  • go 中没有“继承”,只是在顶部加上一些语法糖的组合。

标签: inheritance go


【解决方案1】:

正如 JimB 所说,Go 中没有像其他语言那样适当的继承。为了帮助可视化这一点,让我们把你的代码放在main()

a := &A{}
b := &B{}

a.Parse()
b.Parse()

a.Parse() 被调用时,Go 编译器会检查a 是否有方法Parse(),并且确实有。所以它调用了方法a.Parse

b.Parse() 被调用时,Go 编译器会检查b 是否有方法Parse(),但它没有——但结构中的嵌入字段有!所以它只是使用该字段中的方法,因此会调用b.A.Parse()。实际上,您可以将 B 更改为:

type B struct {
    A A
}

唯一的区别是b.Parse() 不起作用,您必须手动指定.A(因此是b.A.Parse()),但它在功能上保持不变。


进一步阅读:

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    相关资源
    最近更新 更多