Accessing variables across packages in Go

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

Accessing variables across packages in Go

问题

package main的范围内,我有两个变量,它们分别是:

var (
    app Application
    cfg Config
)

现在,由于我的应用程序的规模开始增加,我决定将网站的每个模块放在自己的包中,就像一个子目录一样,例如:

/src/github.com/Adel92/Sophie
  + user/   (user包)
     - register.go
     - login.go
     - password.go
  + topic/  (topic包)
     - ...等等
  - main.go (main包)

我该如何从其他包中访问appcfg这两个全局变量?这样做是错误的吗?我有一种感觉是错误的。

如果是这样的话,我该如何在它们自己的命名空间中声明函数,这样我就不必一直使用带有usertopic前缀的名称了。

英文:

I have two variables in the scope of package main, those would be these:

var (
	app Application
	cfg Config
)

Now, since the size of my application is starting to increase, I have decided to put each module of the website in its own package, much like a subdirectory as so:

/src/github.com/Adel92/Sophie
  + user/   (package user)
     - register.go
     - login.go
     - password.go
  + topic/  (package topic)
     - ... etc
  - main.go (package main)

How would I go around around accessing the app and cfg global variables from other packages? Is this the wrong way to go about it? I have a feeling it is.

In that case, how would I declare functions in their own namespace so I don't have to go crazy with names that are affixed with user and topic all the time.

答案1

得分: 11

首先,大写的变量名可以导出以供其他包访问,所以AppCfg是可以使用的。然而,通常不建议使用子包进行命名空间管理;包应该用于离散、自包含的功能,因此以这种方式使用它们通常会带来更多麻烦(例如,导入循环是严格不可能的,所以如果你在这种布局中有两个需要相互通信的子包,那么你就没办法了)。

如果你发现你需要在变量前加上usertopic以避免名称冲突,那么也许底层概念应该被分解为自己的包,然后你可以为usertopic分别创建一个实例。

英文:

Capitalized variable names are exported for access in other packages, so App and Cfg would work. However, using sub-packages for name-spacing is generally not recommended; packages are intended for discrete, self-contained functionality so it is usually more trouble than it's worth to use them this way (for example, import cycles are strictly impossible, so if you have two sub-packages in this layout that need to talk to each other then you're out of luck).

If you're finding you need to prefix things with user and topic in order to avoid name collisions, then perhaps the underlying concept should be factored into its own package, and you can create one instance of it for user and one for topic?

huangapple
  • 本文由 发表于 2014年3月30日 02:46:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/22735325.html
匿名

发表评论

匿名网友

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

确定