Using reflect, how to check if an embedding type overrides a method of the embedded type?

281 Views Asked by At

With embedded types, how can I distinguish using package reflect if a type is implementing a given interface through the embedded type or if it has its own implementation of the method that overrides the implementation of the embedded type?

Concrete example (full example on play.golang.org):

type A string

func (a A) String() string {
    return string(a)
}

type A1 struct {
    A
}

type A2 struct {
    A
}

func (a A2) String() string {
    return strings.ReplaceAll(string(a.A), " ", "_")
}

var (
    a1 A1
    a2 A2
)

When inspecting a1 and a2 using reflect, how can I tell that the implementation of method String in A1 is inherited while method String in A2 is directly attached to A2?

I tried to compare reflect.TypeOf(a1).MethodByName("String").Func with reflect.TypeOf(a1).Field(0).Type.MethodByName("String").Func but the two values are different.

Note: my real use case is that I want to write unit tests that enforce that if A implements json.Marshaler, a type embedding A has its own implementation of json.Marshaler.

0

There are 0 best solutions below