go – return interface by embedding type-ThrowExceptions

Exception or error:

I need to return an interface. But I get an error:

cannot use B literal (type B) as type K in return argument:
    B does not implement K (missing Check method)

I thought when I embed type I got all the methods of inner type and the interface type as well

package main

import (
    "fmt"
)

type K interface {
    Check()
}

type A struct {
    A string
}

type B struct {
    B A
}

func (a A) Check() {
    fmt.Println(a.A)
}

func newB(a A) K {
    return B{B: a}
}

func main() {
    a := A{A: "A struct"}
    b := newB(a)

    b.Check()

}

how to solve this problem?

How to solve:

This is not embedding:

type B struct {
    B A
}

With the above, you have:

var b B
b.B.Check()

This is embedding:

type B struct {
  A
}

With the above, you have:

var b B
b.Check()

You also have:

b.A.Check()

Answer´╝Ü

B has no Check method and nowhere in your sample code you do any embedding. Just have B implement Check. The error message is pretty clear.

Leave a Reply

Your email address will not be published. Required fields are marked *