转到:从嵌入式结构覆盖接口方法

Consider the following code:

type Intf interface {
    Method()
}

type TypeA struct {
    TypeBInst Intf
}

func (*TypeA) Method() {
    log.Println("TypeA's Method")
}

func (t *TypeA) Specific() {
    t.TypeBInst.Method() // Call override from TypeB
    log.Println("Specific method of TypeA")
}

type TypeB struct {
    *TypeA
}

func (*TypeB) Method() {
    log.Println("TypeB's Method")
}

Is there another way to call func (*TypeB) Method() from inside func (t *TypeA) Specific() than storing a pointer to a TypeB's instance inside the embedded TypeA instance of TypeB? Is it against golang principles?

Working example: playground

Is there another way to call func (*TypeB) Method() from inside func (t *TypeA) Specific() than storing a pointer to a TypeB's instance inside the embedded TypeA instance of TypeB?

Yes, there is:

package main

import "log"

type TypeB struct{}

func (*TypeB) Method() {
    log.Println("TypeB's Method")
}

func main() {
    (*TypeB).Method(nil)
}

But it only works for nilable receivers (without requiring an instance of the receiver).

Is it against golang principles?

Not that I know of, but I personally have never required this in any project ever.