How to make a global variable available to all packages

I have a main.go file that has:

// running the router in port 9000
func main() {
    router,Global := routers.InitApp()
    fmt.println(Global)
    router.RunTLS(":9000" , "domain.crt" , "domain.key")
}

In router.InitMapI want to declare a global variable that can be accessed anywhere in my application. Is it possible? I have tried:

func InitApp() (*gin.Engine,string) {
        var Global= "myvalue"           
        router := gin.New()
        return router,Global


}

But I can’t access the variable Globaleven in the same package.

+18
source share
2 answers

declare a variable at the top level - outside of any functions:

var Global = "myvalue"

func InitApp() (string) {
        var Global= "myvalue"
        return Global

}

Since the variable name begins with an uppercase letter, the variable will be available in the current package by its name, and in any other package when importing the package that defines a variable and assign it the package name like in: return packagename.Global.

( Go: https://play.golang.org/p/h2iVjM6Fpk):

package main

import (
    "fmt"
)

var greeting = "Hello, world!"

func main() {
    fmt.Println(greeting)
}

Go Tour: "" https://tour.golang.org/basics/8 " " https://tour.golang.org/basics/3.

+24

init . , . 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"
}
+3

Source: https://habr.com/ru/post/1649513/


All Articles