从子包中访问全局变量

huangapple go评论84阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年4月20日 22:07:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/43521913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定