英文:
Sharing variables between two source files in the same package
问题
我正在使用Go语言开发一个项目。为了组织代码,我将代码分成了几个文件:
- 与服务器相关的函数放在server.go中
- 数据库处理放在db.go中
- 全局变量放在types.go中
- 等等
我在types.go中声明了一个变量document_root
,并在main.go中进行了定义:
document_root, error := config.GetString("server", "document_root")
在server.go中,我有一个用于生成所请求文件的HTTP状态码的函数,它执行了以下操作:
_, err := os.Stat(document_root + "/" + filename)
在编译时,我遇到了以下错误:
> "document_root declared and not used"
我做错了什么?
英文:
I am working on a project in Go. For organization, I have the code split up into files:
- server related functions go in server.go
- database handling goes in db.go
- global variables are in types.go
- etc.
I declared a variable document_root
in types.go, and defined it in main.go with:
document_root,error := config.GetString("server","document_root")
In server.go, I have a function to generate an HTTP status code for the requested file, and it does:
_, err := os.Stat(document_root+"/"+filename);
Upon compiling, I'm getting this error:
>"document_root declared and not used"
What am I doing wrong?
答案1
得分: 7
我假设在types.go中,你在包范围内声明了document_root
。如果是这样的话,问题出在这一行代码上:
document_root, error := config.GetString("server", "document_root")
在这里,你无意中创建了另一个document_root
变量,它是main
函数内部的局部变量。你需要像这样写:
var err error
document_root, err = config.GetString("server", "document_root")
英文:
I'm assuming in types.go, you're declaring document_root
at the package scope. If so, the problem is this line:
document_root, error := config.GetString("server", "document_root")
Here, you're unintentionally creating another document_root
variable local to the main
function. You need to write something like this:
var err error
document_root, err = config.GetString("server", "document_root")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论