英文:
init() not running in new package
问题
我已经有一段时间没有使用Go语言了,现在我刚刚开始重新处理一个旧项目。
我在一些包中有init()
函数,它们都能正常工作。然而,我刚刚创建了一个新的包,并添加了一个init()
函数,但它不会像其他函数那样在初始化时运行。如果我将init()
函数放在一个之前存在的包中,它就能正常运行...
我相信这是一个简单的问题,但我无论如何都解决不了。我可能做错了什么?
英文:
I haven't used Go in a while and I'm just starting to work on an old project again.
I have init()
functions in a number of the packages and they work fine. However I've just created a new package and added an init()
function but it won't run during initialization like the others. If I put the init()
function in an previously existing package it runs fine...
I believe this is a simple problem but I can't for the life of me figure it out. What could I be doing wrong?
答案1
得分: 12
如果你的主程序根本没有导入你的新包...它的init()
函数将不会被调用。
如果你只想执行已导入包的init()
函数,并且不想使用包的其他内容,你应该将import "foo"
修改为import _ "foo"
。
英文:
If you main program does not import your new package at all... its init()
function would not be called.
If you just want an imported package's init()
function to be executed, and don't want to use package's other content, you should modify import "foo"
to import _ "foo"
.
See init
function (and its full documentation in program execution).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论