英文:
Accessing global var from child package
问题
我正在写一个小的Go应用程序,其中在main.go中定义了一些全局常量,如下所示:
main.go
package main
import (
"github.com/JackBracken/global/sub"
)
const AppName string = "全局字符串"
func main() {
sub.Run()
}
sub/sub.go
package sub
import "fmt"
func Run() {
fmt.Println(AppName)
}
我对Go还不太熟悉,我期望像这样的代码能够工作,但是go build
会抛出错误sub/sub.go:6: undefined: AppName
。
我知道我可以创建一个globals
包,在sub.go
中导入它,并使用globals.AppName
等来引用我的全局变量,但我想知道是否可能按照我的原始方式来做,或者我是否完全误解了作用域和包的概念?
英文:
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?
答案1
得分: 10
你不能在其他地方访问'main'包中的符号,这是因为Go语言不允许导入循环。
如果你需要在'main'包和其他包中访问同一个变量,你需要将变量移到另一个包中,这样两个包都可以访问它。所以你的'globals'包是正确的做法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论