I am writing a small go application that has some global consts defined in main.go like below:
main.go
package main
import (
"github.com/JackBracken/global/sub"
)
const AppName string = "global string"
func main() {
sub.Run()
}
sub/sub.go
package sub
import "fmt"
func Run() {
fmt.Println(AppName)
}
I'm pretty new to Go and would expect something like this to work, but go build
throws the error sub/sub.go:6: undefined: AppName
.
I know I can do something like creating a globals
package, import it in sub.go
and refer to my global variables with globals.AppName
etc., but I'd like to know if it's possible my original way, or am I just completely misunderstanding scoping and packages?
You cannot access symbols in the 'main' package anywhere else, for the simple reason that Go does not allow import loops.
If you need to access a variable in both 'main' and some other package, you'll need to move your variables elsewhere, to a package that both can access. So your 'globals' package is the right idea.
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