Accessing variables across packages in Go

2020-06-16 09:44发布

问题:

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:

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?



标签: scope go package