dongnai3960 2019-08-08 03:28
浏览 1168

来自不同文件的全局变量Golang

I have two different files: (1) /common/handler.go and (2) main.go.

In the (/common/handler.go) file, I have declared

var db *sql.DB
var err error

as global variables (at the top level, below import). Now, I want to use these two variables in my main.go file because I have this line of code in my main() function:

db, err = sql.Open("mysql","username:password@tcp(127.0.0.1:3306)/test123")

What should I do in order for Go to understand that I was referring to that db and err variables? Am I even doing this the right way? If not, please let me know the best solution.

The reason I split into these two files because I want to make the code cleaner.

Basically, main() in main.go contains

router := mux.NewRouter()
router.HandleFunc("/", common.login)
....

and handler.go contains all the messy stuff.

Thanks,

  • 写回答

1条回答 默认 最新

  • dongpao2871 2019-08-08 04:50
    关注

    "I want to use these two variables in my main.go" You can't because they are unexported, ergo you need to export them.

    "What should I do in order for Go to understand that I was referring to that db and err variables?" You need to qualify them. It's no different from you telling Go with sql.Open that you're referring to the function Open that's declared in the package database/sql.


    Also I recommend you take the Tour of Go.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)