matlabmann
2014-05-08 23:13
浏览 176
已采纳

在包的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 ?

图片转代码服务由CSDN问答提供 功能建议

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

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

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

这是正确的吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doukun8944 2014-05-08 23:20
    最佳回答

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题