Passing Variables to a Golang Package

4.5k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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.