我可以内省 main.main 包的名称吗?
这是一个相当小众的问题,但我目前正在尝试使用 golang 编写一个基于约定的设置存储库。如果我能够以编程方式确定想要存储某些内容(例如“github.net/author/projectname/pkg”)并调用我的库函数的正在运行的包名称,那么这将是一个巨大的 API 福音。
使用Python,可以通过 inspect
模块实现类似的事情,甚至使用 __main__.__file__ 并查看文件系统。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果使用以下函数,您可以获得类似的信息:
runtime.Caller
runtime.FuncForPC
代码可能如下所示
:我把上面的代码(与第一行更改为
runtime.Caller(0)
) 到我安装在GOROOT
中的(随机选择的)Go 库,它打印:或者它打印:
文件名第一行和第二行似乎包含您正在查找的信息。
有两个问题:
如果编译器自动内联函数,可能会给出不正确的结果
对于任何函数
F 定义在包
main
中,函数名为main.F
。例如,如果从main()
调用runtime.Caller(0)
,则函数名称为main.main
,即使>main()
函数在GOROOT/src/github.com/mattn/go-gtk/...
中的 Go 文件中定义。在这种情况下,runtime.Caller
的输出比runtime.FuncForPC
的输出更有用。You can get similar information if you use the following functions:
runtime.Caller
runtime.FuncForPC
The 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
F
defined in packagemain
, the function name is justmain.F
. For example, ifruntime.Caller(0)
is called frommain()
, the function name ismain.main
even if themain()
function is defined in a Go file found inGOROOT/src/github.com/mattn/go-gtk/...
. In this case, the output fromruntime.Caller
is more useful than the output fromruntime.FuncForPC
.