在包的init函数中初始化变量是否可以确保golang应用中的单个实例?

问题描述:

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 ?

我正在编写一个Bloom Filter程序包。 在我的程序包中,我想创建一个 X的实例 code>(非导出),我只想作为一个实例存在; 无论我的软件包被导入应用程序多少次。 p>

我正在做的一个简单代码段是: p>

  package superduperbloomfilter 
 
var x X 
 
func init()  {
x = X.New(....)
} 
  code>  pre> 
 
 

这是正确的吗? p> div>

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.