go - Go 包全局变量在导入中的使用
问题描述
我正在创建一个包,该包将从我在 Go 中拥有的其他服务中调用。如果一个服务导入了这个包,并且这个包有全局变量,组件会将全局变量存储在它自己的内存中吗?
所以如果我的包裹看起来像这样,
var global1 = ""
var global2 = ""
var global3 = ""
var global4 = ""
func setAllGlobalValues() error {
// some logic that checks if globals are nil
// if not setting it to a value after some computation.
// returns nil or an actual error.
}
func DoesSomethingUsingGlobalVars() (bool, error) {
// sets and uses the global vars.
// Does some sort of computation and returns a bool, nil or nil,error
}
然后在服务中我会导入这个包并使用这个doesSomethingUsingGlobalVars
功能。使用这个包的组件会将全局变量存储在自己的内存中吗?我现在无法用我的服务来测试它的设置方式,所以我很好奇是否有人知道。
从本质上讲,这是否有效,或者每次从导入此包的服务调用任何内容时,全局变量是否为零?
提前谢谢大家!
解决方案
It seems as if you are trying to reinvent objects. Instead of your code, do something like this:
package some
import "fmt"
type Thing struct {
One string
Two string
Three string
Four string
}
func NewThing() Thing {
return Thing{"One", "Two", "Three", "Four"}
}
func (t Thing) Print() {
fmt.Println(t.One, t.Two, t.Three, t.Four)
}
Then, the "global variables" are only calculated once, when you call NewThing
.
推荐阅读
- javascript - CSS Shadow Parts Selector ::part() 不能与 Chrome 中的 :disabled 伪类结合使用
- python - 带有所需参数的单元测试测试 get_arguments
- bash - 将 bash 时间函数解析为秒
- rbvmomi - 有没有办法找到 RbVmomi::VIM::VirtualMachine 实例的所有者?
- debian - 如何获取双频wifi设备的两个MAC地址?
- apache-kafka - 如何让多个 Kafka 代理复制
- opencv - OpenCV 中是否有类似于 halcon 中的 'gen_measure_rectangle2' 的函数?
- tomcat - 从源代码安装 Axelor 6.0.8 和 tomcat?
- git - Azure-Devops 使用默认的 git hook 脚本创建新的仓库
- android - 如何打开图库(不让用户在图库到照片应用程序之间进行选择)