How to have a global variable accessible across all packages

后端 未结 2 1064
暗喜
暗喜 2021-02-03 22:56

I have a main.go file which has:

// running the router in port 9000
func main() {
    router,Global := routers.InitApp()
    fmt.println(Global)
    router.RunTL         


        
相关标签:
2条回答
  • 2021-02-03 23:39

    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"
    }
    
    0 讨论(0)
  • 2021-02-03 23:46

    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.

    0 讨论(0)
提交回复
热议问题