0

When reflect.TypeOf is used on functions, resultant object has empty PkgPath(). Full example showing this is as follows:

// file 1, package foo:
func New() *Foo {
  return nil
}

// file 2, package main, main func:
typ := reflect.TypeOf(foo.New)
fmt.Printf("typ.PkgPath() is '%s'\n", typ.PkgPath())

Do I understand right that there is no need to get pkg path from functions and there is no way to learn it given reflect.Type alone for funcs? If not - is there still a way to extract it somehow?

Edit 1: the problem I'm trying to solve is to write a code generator that would create a code doing something with the functions that I'm passing to that code generator. Code generator is a library that gets called in my utility's main function that should somehow take functions that I define in some packages and create code that somehow uses those functions.

Alex
  • 2,916
  • 3
  • 22
  • 27
  • I hope I understood your question correctly, If not, please advise. – Jonathan Hall Nov 05 '19 at 20:37
  • 2
    The value passed to reflect.TypeOf has anonymous type `func() *Foo`. Anonymous types do not have a package path. Describe the higher-level problem that you are trying to solve. There may be a solution to that problem. – Charlie Tumahai Nov 05 '19 at 20:38
  • 1
    For example: https://play.golang.org/p/qyUvU1Ej1Jq – JimB Nov 05 '19 at 20:43
  • @CeriseLimón added a problem I'm trying to solve. Seeing example above it seems I can't solve it using reflection alone as I'd need to define a type somehow. – Alex Nov 05 '19 at 20:47
  • @Flimzy updated context for this question. Looks like the answer is still no, but wanted to see if there are possible options. Question that you reference deals with the type reference, not the function reference as in my snippet above. – Alex Nov 05 '19 at 20:50
  • 1
    Package functions have anonymous types. There's no way to get any package information from an anonymous type; it's anonymous. It also has no name, for the same reason. You can see here: https://play.golang.org/p/nRfKzxjVzph – Adrian Nov 05 '19 at 20:53
  • Understood, that's what I thought is happening too. So, in order to refer to those functions, I have no other way but to give package information along with reflect.TypeOf(somePackageFunction). Passing package names seems like a hack, but looks like I can't avoid it. Thanks! – Alex Nov 05 '19 at 20:55
  • 2
    Code generators typically work from the source code, not from the runtime values. The import path of the function is known to the programmer who typed the expression `foo.New`. Explicitly include that path in the code if you go down the path of using runtime values. – Charlie Tumahai Nov 05 '19 at 20:57
  • I see, I had my reasons to do it that way - primarily due to extreme simplicity of the code generator - I wanted to have things defined in one place, instructions to code generator are too lengthy to pack them into a list of parameters to go generate. – Alex Nov 05 '19 at 21:01

0 Answers0