How to organize Go code with packages?
For small programs, you probably don’t need to define another package other than the special package: main. For bigger programs, you might need to define your own packages to organize your code. For people who work on the same code to create many programs, they may need to define their own libraries and import these to their own programs.
In my own projects, I create a cmd folder to keep entry-point applications of my program, then I do dependency-injection and other orchestration code there. All of the other code lives inside internal folders and not get reused by the outer packages other than the ones in my program.
Splitting packages into sub-directories
You can split packages into subdirectories, Go stdlib uses this style. Look at http package for example. It’s inside net package. Http things belong to network things, so, they put it under net package. However, that doesn’t mean that, http package can use net package’s internals, it cannot. Each go package is a different beast on its own, there’s no relationship between net and http package in stdlib other than the organization purposes.
Go provides no sub-packaging mechanism and when you split up your packages to organize your BIG package, you may make some of the internals of your package to the outside world, and so, anyone can import them. You may not want this, so, internal package convention prevents your packages to be imported from unwanted parties. I explain internal packages here in this post.
And, last, new gophers who are beginning to Go, create, src/ folders, you don’t need to do that. Just put your source files into your project root. It’s better that way.
You made it here! Thanks for reading! And please support me: Follow my publication. and add claps to my post! Encourage me to write more.
I’m mostly tweeting about Go, you can follow me on twitter: @inancgumus.
You will receive Go tips, tutorials and notifications about my upcoming online Go course.
Originally published at blog.learngoprogramming.com on September 26, 2017.
Create your free account to unlock your custom reading experience.