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

egg*_*rtx 4 http global-variables go

我正在Go开展一个项目.对于组织,我将代码拆分为文件:

  • 服务器相关的功能进入server.go
  • 数据库处理在db.go中
  • 全局变量在types.go中
  • 等等

document_roottypes.go中声明了一个变量,并在main.go中定义了:

document_root,error := config.GetString("server","document_root")
Run Code Online (Sandbox Code Playgroud)

server.go中,我有一个为所请求文件生成HTTP状态代码的函数,它执行以下操作:

_, err := os.Stat(document_root+"/"+filename);
Run Code Online (Sandbox Code Playgroud)

编译后,我收到此错误:

"document_root已声明且未使用"

我究竟做错了什么?

Eva*_*haw 7

我假设在types.go中,你document_root在包装范围内声明.如果是这样,问题是这一行:

document_root, error := config.GetString("server", "document_root")
Run Code Online (Sandbox Code Playgroud)

在这里,您无意中document_rootmain函数本地创建了另一个变量.你需要写这样的东西:

var err error
document_root, err = config.GetString("server", "document_root")
Run Code Online (Sandbox Code Playgroud)