如何在所有包中访问全局变量 [英] How to have a global variable accessible across all packages
问题描述
我有一个main.go文件,其中包含:
I have a main.go file which has:
// running the router in port 9000
func main() {
router,Global := routers.InitApp()
fmt.println(Global)
router.RunTLS(":9000" , "domain.crt" , "domain.key")
}
在 router.InitMap
中,我想声明一个全局变量,该变量可以在我的应用程序中的任何位置进行访问.有可能吗?我试过了:
In router.InitMap
I want to declare a global variable which can be accessed throughout my application anywhere. Is is possible? I tried:
func InitApp() (*gin.Engine,string) {
var Global= "myvalue"
router := gin.New()
return router,Global
}
但是即使在同一包中,我也无法访问变量 Global
.
But I can't access the variable Global
even in the same package.
推荐答案
在所有函数之外的顶级声明一个变量:
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
.
这是另一个示例(也在Go游乐场中: https://play.golang.org/p/h2iVjM6Fpk ):
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)
}
另请参阅Go Tour:变量" https://tour.golang.org/basics/8 和导出的名称" https://tour.golang.org/basics/3
See also Go Tour: "Variables" https://tour.golang.org/basics/8 and "Exported names" https://tour.golang.org/basics/3.
这篇关于如何在所有包中访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!