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

10

3 Answers

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
2

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!

2

I suggest use the common way of import.

First I will explain the way it called "relative import" maybe this way cause of some error

Second I will explain the common way of import.

FIRST:

In go version >= 1.12 there is some new tips about import file and somethings changed.

1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"

2- You have to use uppercase when you want to import a file!

3- Use Uppercase for variables, structures and functions that you want to import in another files

Notice: There is no way to import the main.go in another file.

file directory is:

root
|_____main.go
|_____model |_____example.go

this is a example.go:

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

and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase

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

NOTE!!!

NOTE: I don't recommend this this type of import!

SECOND:

(normal import)

the better way import file is:

your structure should be like this:

root
|_____github.com |_________Your-account-name-in-github | |__________Your-project-name | |________main.go | |________handlers | |________models | |_________gorilla |__________sessions

and this is a example:

package main
import ( ""
)
func main(){ //you can use sessions here
}

so you can import "" in every where that you want...just import it.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like