The problem of global variables in Golang.
------------------------------------------------------------------
17down Votefavorite1
I ' m fairly new to Golang, this should is a simple answer but I ' ve tried searching every where with no luck.
How does I access a global variable that is declared/init in my main.go in a different. Go package/file? Keeps telling me, the variable is undefined (I-know that global variables was bad and this is just to be used as a Tim Estamp)
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 mainshareEditEditedJan ' at 13:51AskedJan ' at 13:36Nighthee18311
- 2 Possible Duplicate of Go build works fine but go run fails–ainar-g Jan "at 13:42"
- is the first letter of the variable name capitalized?–olif Jan ' at 13:43
- Yes, it is capitalized, and my go build fails–nighthee Jan "at 13:44
- is including all relevant files when is running the program ? That's, when running the code, was you running go run File1.go file2.go. Etc–olif Jan at 13:45
- Yes, to is more concise, I has a variable called ' var StartTime = time. Now () ' In my main.go if I try to access StartTime in a different. Go for the same directory, it says its undefined, W Ould I has to include "main" in the. go file, which im trying to call? –nighthee Jan at 13:47
Show
5More Comments2 Answersactiveoldestvotesup vote33down voteaccepted
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
ShareEditEditedJan ' at 14:19answeredJan ' at 13:57Olif1,3301
- Yep It worked! thanks! –nighthee Jan at 14:34
Add a Commentup vote3down vote
I Create a file dif.go
that contains your code:
package difimport ( "time")var StartTime = time.Now()
Outside the folder I create my main.go
, it is ok!
package mainimport ( 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!
ShareEditEditedNov ' at 5:40Hi I ' m frogatto17.8k5 answeredJan ' at 14:02Joy Miao3
- My ' dif ' is a restful API and won ' t being called when the program starts but only if its invoked through URL, so I need To put the StartTime in Main.go and pass it to dif, you ' re passing it from dif to main, thanks for the try Though! –nighthee Jan at 14:05
Golang Global Variable Access