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
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 .
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.
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.
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).
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With