Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables across packages in Go

Tags:

scope

package

go

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.

like image 446
Jesse Brands Avatar asked Mar 29 '14 18:03

Jesse Brands


1 Answers

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?

like image 103
Evan Avatar answered Oct 19 '22 07:10

Evan