继承 – Golang方法覆盖

我有以下内容:

type Base struct {

}

func(base *Base) Get() string {
    return "base"
}

func(base *Base) GetName() string {
    return base.Get()
}

我想用一个新的Get()实现来定义一个新类型,这样我就可以使用新类型代替Base,并且在调用GetName()的地方调用新的Get()实现.如果我使用Java,我将继承Base并覆盖Get().我应该如何在Go中实现这一目标?我希望尽可能避免破坏更改,因此不需要更改Base的现有使用者.

我对此的第一次尝试看起来像……

type Sub struct {
    Base
}

func(sub *Sub) Get() string {
    return "Sub"
}

..哪个不起作用.我的脑子还没有清楚地连接Go.

最佳答案 Go不是“经典”的OO语言:它不知道类和继承的概念.

然而,它确实包含非常灵活的接口概念,可以使用面向对象的许多方面. Go中的接口提供了一种指定对象行为的方法:如果某些东西可以做到这一点,那么它可以在这里使用.

接口定义了一组方法,但这些方法不包含代码:它们未实现(这意味着它们是抽象的).

因此,在同一方法中使用不同类型的方法是使用接口.

以下是证明它的简单示例:

package main

import (
    "fmt"
)

type Base struct{}
type Baser interface {
    Get() float32
}

type TypeOne struct {
    value float32
    Base
}

type TypeTwo struct {
    value float32
    Base
}

type TypeThree struct {
    value float32
    Base
}

func (t *TypeOne) Get() float32 {
    return t.value
}

func (t *TypeTwo) Get() float32 {
    return t.value * t.value
}

func (t *TypeThree) Get() float32 {
    return t.value + t.value
}

func main() {
    base := Base{}
    t1 := &TypeOne{1, base}
    t2 := &TypeTwo{2, base}
    t3 := &TypeThree{4, base}

    bases := []Baser{Baser(t1), Baser(t2), Baser(t3)}

    for s, _ := range bases {
        switch bases[s].(type) {
        case *TypeOne:
            fmt.Println("TypeOne")
        case *TypeTwo:
            fmt.Println("TypeTwo")
        case *TypeThree:
            fmt.Println("TypeThree")
        }

        fmt.Printf("The value is:  %f\n", bases[s].Get())
    }   
}

Go Playground

点赞