在整个包中共享全局变量
So I have a SQL pointer (*sql.DB
) that needs shared throughout packages.
For example:
"./main.go
" has a global variable "db
" that needs to be shared with a package in "./another/package.go
".
How could one achieve sharing variables without passing function parameters?
所以我有一个SQL指针( 例如: p>
“ * sql.DB code>),需要在整个包中共享 。 p>
./ main.go code>”具有全局变量“
db ”需要与“
./ another / package.go code>”中的程序包共享。
如何在不传递函数参数的情况下实现共享变量? p> \ n div>
As long as the global variable is exported (meaning its name starts with an uppercase letter: Db *sql.DB
), you can access it in another package through its full name:
package.name.Db
But the alternative to global variable is dependency injection, as in using the inject framework to initialize the correct db.
See "Dependency Injection with Go":
The
inject
library is the result of this work and our solution.
It usesstruct
tags to enable injection, allocates memory for concrete types, and supports injection for interface types as long as they’re unambiguous.
It also has some less often used features like named injection. Roughly, our naive example above now looks something like this:
type AppLoader struct {
MongoService mongo.Service `inject:""`
}
func (l *AppLoader) Get(id uint64) *App {
a := new(App)
l.MongoService.Session().Find(..).One(a)
return a
}
The alternative to VonC's question is to provide a constructor - e.g.
// package datastore
var db *sql.DB
func NewDB(host, port string) (*sql.DB, error) {
// Simplified example
conn, err := sql.Open(...)
if err != nil {
return nil, err
}
db = conn
return conn, nil
}
// package main
func main() {
db, err := datastore.NewDB("localhost", "5432")
if err != nil {
log.Fatal(err)
}
// Now you can use it here, and/or in your datastore package
}
It's typically good practice to use constructors to initialize a package's requirements, and/or pass in a pre-initialized object - e.g. datastore.NewFromExisting(db)
to pass in a pool you've already created.
Where possible your package main
should simply be an entry point for other packages and should try to avoid consuming things on its own.