英文:
Go, Xorm- import xorm instance from other package but will be nil
问题
为什么它是nil?这个问题困扰了我大约三个小时。
main.go
package main
import (
	"sample/db"
)
func main() {    
	println(db.Xorm)       //nil...why...?
}
db/xorm.go
package db
import (
	_ "github.com/lib/pq"
	"xorm.io/xorm"
)
var Xorm *xorm.Engine
func init() {
	url := "user=test host=localhost password=test port=15432 dbname=test sslmode=disable"
	Xorm, err := xorm.NewEngine("postgres", url)
	_ = Xorm
    println(Xorm)           //This is not nil
	if err != nil {
		panic(err)
	}
}
当我在db/xorm.go中定义「SampleVariable string」并从main.go导入时,它将不是nil。
英文:
Why is it nil? It's been bothering me for about three hours.
main.go
package main
import (
	"sample/db"
)
func main() {    
	println(db.Xorm)       //nil...why...?
}
db/xorm.go
package db
import (
	_ "github.com/lib/pq"
	"xorm.io/xorm"
)
var Xorm *xorm.Engine
func init() {
	url := "user=test host=localhost password=test port=15432 dbname=test sslmode=disable"
	Xorm, err := xorm.NewEngine("postgres", url)
	_ = Xorm
    println(Xorm)           //This is not nil
	if err != nil {
		panic(err)
	}
}
When I define 「SampleVariable string」 in db/xorm.go and import from main.go, it will not nil.
答案1
得分: 1
这行代码:
Xorm, err := xorm.NewEngine("postgres", url)
(注意 :=)在 init() 函数的作用域内创建了一个新的局部变量 Xorm,它遮蔽了同名的包级变量,因此包级变量仍然是 nil。
使用 = 而不是 := 进行赋值可以解决这个问题,例如:
var err error
Xorm, err = xorm.NewEngine("postgres", url)
英文:
the line
Xorm, err := xorm.NewEngine("postgres", url)
(notice the :=) is creating a new local variable Xorm inside the init() function's scope that shadows the package level variable with the same name and as a consequence, the package level variable remains nil.
using just = for the assignment should fix the issue, e.g.:
var err error
Xorm, err = xorm.NewEngine("postgres", url)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论