How to have a global variable accessible across all packages
My solution:
define the global variable in other package with Set and Get, similar with class set in python
the good part is that you can set global variables in any package, the bad part is that you can mess up the global variables if you use Set not carefully
https://play.golang.org/p/egApePP7kPq
first define global variable
-- globalvar/globalvar.go --
package globalvar
import "fmt"
var Glbv int
func Set(b int) {
Glbv = b
}
func Get() int {
return Glbv
}
func Pr() {
fmt.Printf("inside globarvar = %v \n", Glbv)
} ```
then you can change the global variable in another package
-- otherpackage/otherpackage.go --
package otherpackage
import (
"fmt"
"play.ground/globalvar"
)
func Bar() {
globalvar.Set(3)
}
func Prtf() {
var cc = globalvar.Get()
fmt.Printf("inside otherpackage globalvar=%v \n", cc)
}
main function
package main
import (
"play.ground/globalvar"
"play.ground/otherpackage"
)
func main() {
globalvar.Pr()
otherpackage.Prtf()
globalvar.Set(2)
globalvar.Pr()
otherpackage.Prtf()
otherpackage.Bar()
globalvar.Pr()
otherpackage.Prtf()
}
here is the result
inside globarvar = 0
inside otherpackage globalvar=0
inside globarvar = 2
inside otherpackage globalvar=2
inside globarvar = 3
inside otherpackage globalvar=3
declare a variable at the top level - outside of any functions:
var Global = "myvalue"
func InitApp() (string) {
var Global= "myvalue"
return Global
}
Since the name of the variable starts with an uppercase letter, the variable will be available both in the current package through its name - and in any other package when you import the package defining the variable and qualify it with the package name as in: return packagename.Global
.
Here's another illustration (also in the Go playground: https://play.golang.org/p/h2iVjM6Fpk):
package main
import (
"fmt"
)
var greeting = "Hello, world!"
func main() {
fmt.Println(greeting)
}
See also Go Tour: "Variables" https://tour.golang.org/basics/8 and "Exported names" https://tour.golang.org/basics/3.
It is better to use the init function for initialisation of global variables. It also will be processed only once even in multiply includes of this package. https://play.golang.org/p/0PJuXvWRoSr
package main
import (
"fmt"
)
var Global string
func init() {
Global = InitApp()
}
func main() {
fmt.Println(Global)
}
func InitApp() (string) {
return "myvalue"
}