且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Golang:如何在包中的文件使用全局变量?

更新时间:2023-11-14 09:08:10

Edit: The problem is that you used Short variable declaration := and you just stored the created *DB value in a local variable and not in the global one.

This line:

db, err := NewDB(dbinfo)

Creates 2 local variables: db and err, and this local db has nothing to do with your global db variable. Your global variable will remain nil. You have to assign the created *DB to the global variable. Do not use short variable declaration but simple assignment, e.g:

var err error
db, err = NewDB(dbinfo)
if err != nil {
    log.Fatal(err)
}

Original answer follows.


It's a pointer type, you have to initialize it before you use it. The zero value for pointer types is nil.

You don't have to export it (that's what starting it with a capital letter does). Note that it doesn't matter that you have multiple files as long as they are part of the same package, they can access identifiers defined in one another.

A good solution would be to do it in the package init() function which is called automatically.

Note that sql.Open() may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping().

For example:

var db *sql.DB

func init() {
    var err error
    db, err = sql.Open("yourdrivername", "somesource")
    if err != nil {
        log.Fatal(err)
    }
    if err = db.Ping(); err != nil {
        log.Fatal(err)
    }
}

相关阅读

推荐文章