Go - Golang Global Variable access

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m fairly new to golang, this should be a simple answer but I ve tried searching every where with no luck.

How do I access a global variable that was declared/init in my main.go in a different .go package/file? Keeps telling me that the variable is undefined (I know that global variables are bad but this is just to be used as a timestamp)

in main.go

var StartTime = time.Now()
func main(){...}

trying to access StartTime in a different .go file but keep getting StartTime undefined

Answers

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/35038864/golang-global-variable-access

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils