douken7402 2012-10-11 01:00
浏览 68
已采纳

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

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条回答 默认 最新

  • doubaisui2526 2012-10-11 01:49
    关注

    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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用