Access to variables through packages in Go

I have two variables in the scope of the package main , these will be the following:

 var ( app Application cfg Config ) 

Now, as the size of my application starts to increase, I decided to put each module of the website in a separate package, very similar to a subdirectory:

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

How can I access the app and cfg global variables from other packages? Is this the wrong way? I have a feeling.

In this case, how would I declare functions in their own namespace so that I don’t have to go crazy with names that are constantly attached to user and topic .

+7
source share
1 answer

The names of capitalized variables are exported for access in other packages, so App and Cfg will work. However, using subpackages for a namespace is usually not recommended; packages are intended for discrete, autonomous functions, so there are usually more problems than using them this way (for example, import cycles are strictly impossible, therefore, if you have two subpackages in this layout that need to talk to each other, then you are out of luck )

If you find that you need prefix things with user and topic to avoid name collisions, maybe the basic concept should be taken into account in its own package, and you can create one instance for it user and one for topic ?

+8
source

All Articles