首页 > 解决方案 > 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功能。使用这个包的组件会将全局变量存储在自己的内存中吗?我现在无法用我的服务来测试它的设置方式,所以我很好奇是否有人知道。

从本质上讲,这是否有效,或者每次从导入此包的服务调用任何内容时,全局变量是否为零?

提前谢谢大家!

标签: gomemorypackagecomponents

解决方案


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.


推荐阅读