英文:
Does initializing a variable in the init function of a package ensures a single instance in a golang app?
问题
我正在编写一个布隆过滤器包。在我的包中,我想创建一个X
的实例(非导出的),我希望它只存在一个实例,无论我的包被导入到应用程序中多少次。
我正在做的简单示例代码如下:
package superduperbloomfilter
var x X
func init() {
x = X.New(....)
}
这样做正确吗?
英文:
I am writing a Bloom Filter package.
Within my package, I want to create an instance of X
(non-exported) which I want to exist only as a single instance; no matter how many times my package is imported into an app.
A simple snippet of what I am doing is:
package superduperbloomfilter
var x X
func init() {
x = X.New(....)
}
Is this correct ?
答案1
得分: 8
根据规范,导入的包只会被初始化一次:
如果一个包有导入,那么在初始化该包本身之前,导入的包会被先初始化。如果多个包导入了包P,那么P只会被初始化一次。
英文:
> which I want to exist only as a single instance; no matter how many
> times my package is imported into an app
The spec says an imported package is initialized only once:
> If a package has imports, the imported packages are initialized before
> initializing the package itself. If multiple packages import a package
> P, P will be initialized only once.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论