使用包作为全局变量的存储器。

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

Using package as store for global variables

问题

我正在学习golang,并且在我的第一个任务中开始构建一个简单的网站。问题是我需要一些全局变量,我了解到使用上下文传递这些全局变量是不明智的,因为每个请求的上下文都应该是不同的。因此,我考虑创建一个包,在main()函数中填充所需的变量。我在其他项目中没有看到这种解决方案,所以我想知道这样做是否正确?

config包的简单示例:

package config
var DB *sql.DB

然后在main函数中:

package main
import "project/config"
func main() {
 config.DB, err = sql.Open("postgres", conn)
 if err != nil {
	panic(err)
 }
}

然后我只需要导入config包,并在需要的地方获取变量。

英文:

I'm learning golang and for my first task I have started to build a simple website. The problem is that I need to have some globals available, I have learned that it is not wise to send these globals using context, as context should be different for every request. Therefore I have thought about creating a package that will be filled with needed variables in main(). I haven't seen this solution in other projects, so I'm asking if this is wrong?
Simple example of config package:

package config
var DB *sql.DB

And the main:

package main
import "project/config"
func main() {
 config.DB, err = sql.Open("postgres", conn)
 if err != nil {
	panic(err)
 }
}

Then I would just import the config package and get the variable wherever I need.

答案1

得分: 1

这种方法没有问题。你也可以使用init()函数来初始化全局变量,而不是使用main()函数。

英文:

There is nothing wrong with this approach. Also you can use init() function instead of main() to initialize your global variables.

答案2

得分: 0

确实,这是一个非常好的解决方案。

英文:

Indeed, that is a very nice solution.

huangapple
  • 本文由 发表于 2017年2月4日 18:49:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/42039453.html
匿名

发表评论

匿名网友

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

确定