golang 中全局变量的问题。
------------------------------------------------------------------
17down votefavorite 1I‘m fairly new to golang, this should be a simple answer but I‘ve tried searching every where with no luck.
How do I access a global 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
variables
go
global
main
share
edit
edited Jan 27 ‘16 at 13:51 asked
Jan 27 ‘16 at 13:36
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
share
edit
edited Jan 27 ‘16 at 14:19 answered
Jan 27 ‘16 at 13:57
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!
share edit edited Nov 26 ‘17 at 5:40
Hi I‘m Frogatto
17.8k54887 answered
Jan 27 ‘16 at 14:02
joy miao
713