Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing global var from child package

Tags:

go

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?

like image 345
Jack Bracken Avatar asked Sep 01 '25 22:09

Jack Bracken


1 Answers

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.

like image 173
Flimzy Avatar answered Sep 03 '25 18:09

Flimzy