Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variables

How do I access a variable that was declared/init in my main.go in a different .go package/file? Keeps telling me that the variable is undefined (I know that global variables are bad but this is just to be used as a timestamp)

in main.go

var StartTime = time.Now() func main(){...} 

trying to access StartTime in a different .go file but keep getting StartTime undefined

like image 392
Nighthee Avatar asked Jan 27 '16 13:01

Nighthee


People also ask

Where can I find global variables?

Global variable values are stored in a separate file on a disk or on a NiceLabel Control Center. By default, your global variable storage location is set to C:\ProgramData\ NiceLabel \Global Variables\ . The file name is Globals. tdb .

How do you access global variables in Python?

Rules of global keyword: If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global. Variables that are only referenced inside a function are implicitly global. We use a global keyword to use a global variable inside a function.

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 functions access global variables?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).


2 Answers

I create a file dif.go that contains your code:

package dif  import (     "time" )  var StartTime = time.Now() 

Outside the folder I create my main.go, it is ok!

package main  import (     dif "./dif"     "fmt" )  func main() {     fmt.Println(dif.StartTime) } 

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST 

Files directory structure:

folder   main.go   dif     dif.go 

It works!

like image 45
joy miao Avatar answered Sep 28 '22 05:09

joy miao


I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now() func main() {    otherPackage.StartTime = StartTime } 

otherpackage.go

var StartTime time.Time 
like image 84
olif Avatar answered Sep 28 '22 04:09

olif