is it possible to call overridden method from parent struct in Golang?

后端 未结 6 1523
攒了一身酷
攒了一身酷 2020-11-27 04:34

I want to implement such code, where B inherit from A and only override A\'s Foo() method, and I hope the code to print B.Foo(), but it still print A.Foo(), it seems that th

6条回答
  •  攒了一身酷
    2020-11-27 05:05

    Recently I have a need to do this and the composition method proposed by OP works great.

    I try to create another example to try to demonstrate the parent and child relationship and make it easier to read.

    https://play.golang.org/p/9EmWhpyjHf:

    package main
    
    import (
        "fmt"
        "log"
    )
    
    type FruitType interface {
        Wash() FruitType
        Eat() string
    }
    
    type Fruit struct {
        name  string
        dirty bool
        fruit FruitType
    }
    
    func (f *Fruit) Wash() FruitType {
        f.dirty = false
        if f.fruit != nil {
            return f.fruit
        }
        return f
    }
    func (f *Fruit) Eat() string {
        if f.dirty {
            return fmt.Sprintf("The %s is dirty, wash it first!", f.name)
        }
        return fmt.Sprintf("%s is so delicious!", f.name)
    }
    
    type Orange struct {
        *Fruit
    }
    
    func NewOrange() *Orange {
        ft := &Orange{&Fruit{"Orange", true, nil}}
        ft.fruit = ft
        return ft
    }
    func NewApple() *Fruit {
        ft := &Fruit{"apple", true, nil}
        return ft
    }
    
    func (o *Orange) Eat() string {
        return "The orange is so sour!"
    }
    
    func main() {
        log.Println(NewApple().Eat())
        log.Println(NewApple().Wash().Eat())
        log.Println(NewOrange().Eat())
        log.Println(NewOrange().Wash().Eat())
    }
    

提交回复
热议问题