thatdevop
thatdevop

Reputation: 1039

Go package Global Variable usage within imports

I am creating a package that will be called from other services that I have in Go. If a service imports this package, and this package has global variables, will the component store the global variables in its' own memory?

So if my package looks something like this,

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
}

Then in the service I would import this package and use the doesSomethingUsingGlobalVars function. Will the component using this package store the global variables in its own memory? I can't really test it now with my services with the way things are set up so I'm just curious if anyone knows.

Essentially, will this work or will the global vars be nil each and every-time anything is called from a service that imports this package?

Thanks in advance all!

Upvotes: 0

Views: 1198

Answers (2)

Zombo
Zombo

Reputation: 1

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.

Upvotes: 1

Ben Whaley
Ben Whaley

Reputation: 34416

When your program imports this package, the globals will be set when you call SetAllGlobalValues(), and later, when you call DoesSomethingUsingGlobalVars(), those values will already be set. Note that the first letter of those function names must be capitalized so that they are exported and available for use by other packages. If the variables are not exported, as shown in your code snippet, you will not be able to access them directly from the caller.

Upvotes: 1

Related Questions