This is a fairly niche problem, but I’m currently trying to write a conventions-based settings storage library with golang. It would be a great API boon if I could programmatically determine the running package name that wants to store something (eg "github.net/author/projectname/pkg") calling my library function.
With Python a similar thing could be achieved with the inspect module, or even with __main__.__file__ and a look at the file system.
You can get similar information if you use the following functions:
runtime.Callerruntime.FuncForPCThe code may look like this:
If I put the above code (with the 1st line changed into
runtime.Caller(0)) into a (randomly chosen) Go library which I have installed inGOROOT, it prints:Or it prints:
The filename on the 1st line, and the 2nd line, seem to contain the information you are looking for.
There are two problems:
It may give incorrect result if functions are automatically inlined by the compiler
For any function
Fdefined in packagemain, the function name is justmain.F. For example, ifruntime.Caller(0)is called frommain(), the function name ismain.maineven if themain()function is defined in a Go file found inGOROOT/src/github.com/mattn/go-gtk/.... In this case, the output fromruntime.Calleris more useful than the output fromruntime.FuncForPC.