且构网

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

如何跨包中的文件使用全局变量?

更新时间:2023-11-14 09:12:34

问题是你使用了 短变量声明 := 并且您只是将创建的 *DB 值存储在局部变量中而不是全局变量中.

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.

这一行:

db, err := NewDB(dbinfo)

创建2个局部变量:dberr,这个局部db和你的全局db无关代码>变量.您的全局变量将保持 nil.您必须将创建的 *DB 分配给全局变量.不要使用简短的变量声明,而是使用简单的赋值,例如:

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)
}

原始答案如下.

它是一个指针类型,使用前必须初始化.指针类型的零值是 nil.

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.

一个好的解决方案是在自动调用的包 init() 函数中执行此操作.

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

请注意,sql.Open() 可能只需验证其参数,而无需创建与数据库的连接.要验证数据源名称是否有效,请调用 DB.Ping().

例如:

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)
    }
}