How to call a child method in a parent method?

package main

import "fmt"

type Super struct{}

func (super *Super) name() string {
    return "Super"
}

func (super *Super) WhoAmI() {
    fmt.Printf("I'm %s.\n", super.name())
}

type Sub struct {
    Super
}

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

func main() {
    sub := &Sub{Super{}}
    sub.WhoAmI()
}

I want to get "I'm Sub," but instead I get "I'm Super."

I already know that sub.WhoAmI will call sub.Super.WhoAmI, but I still want to know if there is a way to get "I'm Sub". In Python, when I write the following code:

class Super(object):

    def name(self):
        return "Super"

    def WhoAmI(self):
        print("I'm {name}".format(name=self.name()))

class Sub(Super):

    def name(self):
        return "Sub"


if __name__ == "__main__":
    sub  = Sub()
    sub.WhoAmI()

I can get "I'm Sub."

+4
source share
2 answers

An attachment is not a subclass. There are no superclasses or subclasses in Go. Subhere is not a "child" of Super. It contains a Super. You cannot do this. You need to organize your code differently so that it does not need.

, ( ) Go:

package main

import "fmt"

type Namer interface {
    Name() string
}

type Super struct{}

func (sub *Super) Name() string {
    return "Super"
}

type Sub struct{}

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

func WhoAmI(namer Namer) {
    fmt.Printf("I'm %s.\n", namer.Name())
}

func main() {
    sub := &Sub{}
    WhoAmI(sub)
}

, ( Go), . , , , . , , .

+7

Go, . Go , , , , , .

, ​​:

func (f *Foo) DoStuff()

, :

func DoStuff(f *Foo)

, , Go name Super - , . ( , WhoAmI Super super *Super, Go .)

, , :

http://play.golang.org/p/8ELw-9e7Re

package main

import "fmt"

type Indentifier interface {
    WhoAmI() string
}

type A struct{}

func (a *A) WhoAmI() string {
    return "A"
}

type B struct{}

func (b *B) WhoAmI() string {
    return "B"
}

func doSomething(x Indentifier) {
    fmt.Println("x is a", x.WhoAmI())
}

func main() {
    doSomething(&A{})
    doSomething(&B{})
}
+2

Source: https://habr.com/ru/post/1616392/


All Articles