mardi 14 mai 2019

Why typeof(method) does not return reflect.Method instance?

Let's say I have Foo struct with a method defined as follows:

type Foo struct {
    Name string
}

func (f *Foo) Get(a int, b string) (string, error) {
    return f.Name, nil
}

If I write

obj := &Foo{}
t := reflect.TypeOf(obj.Get)

t.Kind() returns reflect.Func and apparently I have no way to access information that Get func I extracted type information from "belongs" to the Foo struct, that is receiver is of Foo type, it is not even surfaced in the in-parameters.

I guess that's intentional and I miss something fundamental about functions that made language authors throw away receiver information for typeof operations applied to method references.

I have two questions:

  1. Am I correct and there is no way to get receiver type in the snippet with TypeOf call above?
  2. What are the alternatives I have if I want to pass reflection information about a method to some code that intends to analyze function and related receiver (that is, in essence a method)?

Trying to answer second question myself and based on what I see in the official documentation, it looks like my only options are to either pass TypeOf(receiver) and TypeOf(receiver.method) or TypeOf(receiver) and the name of the receiver's method.





Aucun commentaire:

Enregistrer un commentaire