init()在新包中未运行。

huangapple go评论80阅读模式
英文:

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"

参见init函数(以及其在程序执行中的完整文档)。

英文:

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).

huangapple
  • 本文由 发表于 2017年1月27日 13:45:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/41887640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定