英文:
Go: "instance" redeclared in this block
问题
我有这两个文件:
daoFactory.go
package dao
import "sync"
type daoFactory struct {}
var instance *daoFactory
//一些函数
fakeProvisionDao.go
package dao
import (
"sync"
"model"
)
type provisionDao struct {
}
var instance *provisionDao
//一些函数
这两个文件都在同一个包dao
中。
我得到了这个错误:
> 在此块中重新声明了"instance"
显然,问题的原因是instance
变量在两个文件中都被声明了。我刚开始学习Go编程,不知道应该如何处理这个错误。
英文:
I have these two files:
daoFactory.go
package dao
import "sync"
type daoFactory struct {}
var instance *daoFactory
//some functions
fakeProvisionDao.go
package dao
import (
"sync"
"model"
)
type provisionDao struct {
}
var instance *provisionDao
//some functions
Both are in the same package: dao
.
I get this error:
> "instance" redeclared in this block
Obviously, the cause is that instance
variable is declared in both files. I'm beggining in Go programming and I don't know how should I handle with this error.
答案1
得分: 24
文件对于Go来说没有实际意义,不像Java、Python和许多其他语言,它们只是用来根据你的需要组织代码的。
在Go中,变量在整个package
中可见,这意味着instance
的两个声明都是具有包范围可见性的变量。因此,编译器会抱怨有两个同名的全局变量。
将其中一个实例变量重命名,代码就可以编译通过了。
强烈建议阅读上面评论中的链接;-)
英文:
Files have no real meaning for go, unlike in java, python and many others, they are just for you to organize your code as you see fit.
In go variables are visible package
wide, that means that both declartions of instance
are variables with package wide visibility. Hence the compiler complains about having two global variables with the same name.
Rename any one of your two instance variables and it will compile.
Reading the links in the comments above is highly recommend
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论