3

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.

dolmen
  • 8,126
  • 5
  • 40
  • 42
  • 4
    You may need to examine the source code determine where the method is declared. The go/ast package will be useful for that. Replace "inherited" with "promoted" to avoid the *Go does not have inheritance* downvotes. –  Mar 02 '21 at 16:24
  • 2
    It also doesn't have overrides. I'm curious though *why* you need this information at runtime, because needing to know this implies a fundamental design flaw in the first place, and a likely XY Problem. – Adrian Mar 02 '21 at 16:57
  • 2
    this does not sound like something for a unit test -- it sounds like static analysis, just like all the analyses already done by go vet – JimB Mar 02 '21 at 18:21
  • A unit test probably should test that unmarshaling works correct and shouldn’t be bothered how or why it is correct. – Volker Mar 02 '21 at 22:00
  • @JimB Fair, but I am familiar with the reflect API, not with [go/types](https://golang.org/pkg/go/types/). I want to know if I'm in an area of typing information which is not available at all through reflect. – dolmen Mar 03 '21 at 09:31

0 Answers0