英文:
Passing Variables to a Golang Package
问题
给定一个包含以下局部变量和函数的包:
var bucket *gocb.Bucket
func Init(b *gocb.Bucket) {
bucket = b
}
func DoSomething() {
// 使用 'bucket' 做一些操作
}
在调用依赖于 bucket
变量的 DoSomething
函数之前,是否可以调用 Init
函数并传入 bucket
的实例?
或者,是否应该修改 DoSomething
函数,显式接受一个 bucket
参数,如下所示:
func DoSomething(bucket *gocb.Bucket) {
// 使用 'bucket' 做一些操作
}
我更倾向于在包级别实例化一个 bucket
的单个实例,并在整个应用程序生命周期中使用它,而不是在函数级别进行管理。从设计、性能等方面来看,这种做法是否可行?还是有更好的方法来实现这一点?需要注意的是,bucket
只需要实例化一次。
DoSomething
将从 HTTP 上下文中调用;我希望 HTTP 处理程序不要对 bucket
参数可见,而是在应用程序启动时实例化 bucket
。
英文:
Given a package containing the following local variable and functions:
var bucket *gocb.Bucket
func Init(b *gocb.Bucket) {
bucket = b
}
func DoSomething() {
// do something with 'bucket'
}
Is it acceptable to call the Init
function, passing in an instance of bucket
, before calling DoSomething
, which is dependent on the bucket
variable?
Or, should DoSomething
instead explicitly accept a bucket
parameter, as follows:
func DoSomething(bucket *gocb.Bucket) {
// do something with 'bucket'
}
I would prefer to instantiate a single instance of bucket
at a package-level, and use it throughout the application life-cycle, as opposed to managing at a function-level. Is this acceptable from design, performance, etc., perspectives, or is there a preferred means of achieving this? Bearing in mind that bucket
need only be instantiated once.
DoSomething
will be called from a HTTP context; I would prefer that the HTTP handlers not have visibility on the bucket
parameter, and instead instantiate bucket
on application start-up.
答案1
得分: 4
在Go语言中,如果你的包依赖于外部的某个东西,你需要导入(import)该东西。所以,除非由于某种原因不可能,你应该导入实例化bucket
的包,并从那里继续操作,可以直接赋值给它,或者在你的包的init
函数中进行赋值。
import "my/other/pkg"
var bucket = pkg.InitBucket()
然而,如果无法确定哪个包会提供bucket
,那么你的方式就是正确的。以database/sql
为例,SQL驱动程序在使用之前必须先注册。
总的来说,如果你考虑的是Go包,那么控制反转(IoC)不适用。
英文:
In Go, if your package depends on something external you import said thing. So, unless it's impossible for some reason, you should import the package that instantiates bucket
and take it from there, either directly assigning it or in your package's init
function.
import "my/other/pkg"
var bucket = pkg.InitBucket()
However, if it's impossible to determine what package will provision bucket
, then your way is the way to Go. As an example, consider database/sql
where SQL drivers have to be registered before they can be used.
In general, IoC does not apply to Go packages if that's what you had in mind.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论