-1
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

When I execute method from inherited struct with execute another struct method in it - is executed method from inherited struct, not actual object type.

Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
  • 1
    There is no "inheritance" in go, simply composition with some syntactic sugar on top. – JimB Jun 20 '18 at 21:49

1 Answers1

1

As JimB said, there is no proper inheritance in Go as in other languages. To help visualize this, let's take your code in main():

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

a.Parse()
b.Parse()

When a.Parse() is called, the Go compiler checks if a has a method Parse(), and it does. So it calls the method a.Parse.

When b.Parse() is called, the Go compiler checks if b has a method Parse(), and it does not - but an embedded field inside the struct does! So it simply uses the method from that field, and thus b.A.Parse() is called. In fact, you could change B to this:

type B struct {
    A A
}

And the only difference would be that b.Parse() wouldn't work and that you'd have to specify .A manually (thus b.A.Parse()), but it remains functionally the same.


Further reading:

morganbaz
  • 2,997
  • 1
  • 17
  • 30