登录
首页 >  Golang >  Go问答

Golang 继承和方法重写

来源:stackoverflow

时间:2024-04-13 17:09:32 434浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《Golang 继承和方法重写》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

澄清:我刚刚学习 go,遇到了这个问题。

我正在尝试实现一个“类”,它继承一个方法,该方法调用应由子类实现的“虚拟”方法。这是我的代码:

https://play.golang.org/p/ysiapwarkvl

package main

import (
    "fmt"
    "sync"
)

type Parent struct {
  sync.Mutex
  MyInterface
}

func (p *Parent) Foo() {
  p.Lock()
  defer p.Unlock()
  p.Bar()
}

func (p *Parent) B(){
  panic("NOT IMPLEMENTED")
}

func (p *Parent) A() {
  p.Lock()
  defer p.Unlock()
  p.B()
}

type MyInterface interface {
  Foo()
  Bar()
}

type Child struct {
  Parent
  Name string
}

func (c *Child) Bar(){
  fmt.Println(c.Name)
}

func (c *Child) B(){
  fmt.Println(c.Name)
}

func main() {
  c := new(Child)
  c.Name = "Child"
  // c.A() panic
  c.Foo() // pointer error
}

我遗漏了一些有关sync.mutex 的代码,该代码对child 的值进行一些异步更新。

很明显,在 a() 或 foo() 中,指针 p 具有 parent 类型。我应该如何更改我的代码,以便 a/foo 引用 child 类中定义的 b/bar?


解决方案


当 go 只提供 has-a 关系(组合)时,您需要一个 is-a 关系(继承):

  • go 没有继承,因此两种类型之间不存在 is-a 关系。 child 不是 parent 的一种,因此指向 parent 的指针不能保留指向 child 的指针; child has-a parent 包含在其中。

由于 parentchild 之间不存在 is-a 关系,因此 parent.foo 无法接收 child 类型的对象,也无法使用 child 实现的任何方法。另外,这意味着 parent 不能直接访问 child 上定义的任何方法,例如 bar()b()

通常,parent 不需要调用 child 中的某些方法。如果是这样,您需要向 parent 方法传递一个参数,例如 child 满足的接口,以便您通过该接口调用该方法,或者是调用 child 方法的闭包:

// Use of an interface that Child satisfies.
type Beta interface {
    B()
}
func (p *Parent) A(b Beta) {
    p.Lock()
    defer p.Unlock()
    b.B()
}

// Use of a closure.
func (p *Parent) Foo(bar func()) {
    p.Lock()
    defer p.Unlock()
    bar()
}
func callFoo(p *Parent, c *Child) {
    callBar := func() {
        c.Bar()
    }
    p.Foo(callBar)
}

func (c *Child) Bar() {
    // stub
}

func (c *Child) B() {
    // stub
}

您获得了child可以免费调用parent方法行为,但它仅看起来与继承类似。 child.foo() 实际上执行 child.parent.foo(),这意味着 parent.foo 仍然收到 parent 实例(因此得名),而不是 child 实例。

但是,parent 无法访问 child 未显式共享的任何有关 child 的信息。接口和闭包可以充当两个类之间的机制,类似于 c++ 中的 friend 关键字,但它们比 friend 关键字更具限制性。毕竟,child 不需要与 parent 共享所有内容,只需共享它想要共享的位,有点类似于 this pattern in C++。就我个人而言,我更喜欢这种接口,因为它允许您的 parent“类”与所有类型一起使用满足通用接口,使其与从普通函数或完全不相关的类型的方法调用该方法几乎相同。

理论要掌握,实操不能落!以上关于《Golang 继承和方法重写》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>