在同一个包中的两个源文件之间共享变量

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

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")

huangapple
  • 本文由 发表于 2012年10月11日 09:00:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/12830695.html
匿名

发表评论

匿名网友

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

确定