Go: 在此块中重新声明了”instance”

huangapple go评论76阅读模式
英文:

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 Go: 在此块中重新声明了”instance”

huangapple
  • 本文由 发表于 2015年12月18日 05:02:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/34344172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定