在Go语言应用程序中,将变量初始化在包的init函数中是否确保了单个实例?

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

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
.

huangapple
  • 本文由 发表于 2014年5月9日 07:13:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/23554146.html
匿名

发表评论

匿名网友

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

确定