Background
Yesterday, I wrote database driver part of my project as below
var (
DBdriver = "mysql"
DBinfo = "xxx"
DBengine *xorm.Engine
)
func init() {
DBengine, err := xorm.NewEngine(DBdriver, DBinfo)
...
}
I thought that the DBengine
variable has been declared globally and here even if err
is a new variable, the compiler will assign the return result to the DBengine
of the global variable. but in fact, since :=
is used, DBengine
is also considered as a local variable for creation and assignment.
I ended up changing the code to
func init() {
var err error
DBengine, err = xorm.NewEngine(DBdriver, DBinfo)
...
}
Content
But Iโm wondering why the compiler was designed to create DBengine
as a local variable in such ambiguous cases, instead of prioritizing to see if a variable with the same name has already been declared and assigned to it. I guess, in terms of how the code is written, this just makes the coder create DBengine
before this line if it needs to make it a local variable, which is not much different from my current solution; in terms of the logic of the code, this is more logical and beginner-friendly.
Can anyone explain why the compiler is designed this way and if I have a better way of coding