Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a global variable accessible across all packages

Tags:

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") } 

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   } 

But I can't access the variable Global even in the same package.

like image 365
codec Avatar asked Jul 29 '16 09:07

codec


People also ask

How do you share global variables across modules?

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.

Can global variables be accessed anywhere?

Variables that are created outside of a function are known as Global Variables . A global variable is one that can be accessed anywhere . This means, global variable can be accessed inside or outside of the function.

Can global variables be used across modules in Python?

Globals in Python are global to a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it.

What is the best way to declare and access a global variable?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.


1 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 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.

like image 96
dmitris Avatar answered Sep 19 '22 21:09

dmitris