golang 中全局变量的问题。
------------------------------------------------------------------
I‘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
-
2Possible duplicate of go build works fine but go run fails – Ainar-G Jan 27 ‘16 at 13:42
-
Is the first letter on the variable name capitalized? – olif Jan 27 ‘16 at 13:43
-
Yes, it is capitalized, and my go build fails – Nighthee Jan 27 ‘16 at 13:44
-
are you including all relevant files when running the program? That is, when running the code, are you running go run file1.go file2.go ..etc – olif Jan 27 ‘16 at 13:45
-
Yes, to be more concise, I have a variable called ‘var StartTime = time.Now()‘ in my main.go But when i try to access StartTime in a different .go of the same directory, it says its undefined, would i have to include "main" in the .go file that im trying to call? – Nighthee Jan 27 ‘16 at 13:47
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
-
Yep it worked! Thanks! – Nighthee Jan 27 ‘16 at 14:34
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!
-
My ‘dif‘ is a restful API and won‘t be called when the program starts but only when 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 27 ‘16 at 14:05