What are packages?
A package is nothing but a directory containing one or more Go source files, or other Go packages. Every Go source file must belong to a package and package declaration is done at the top of every source file:By convention, executable programs (ones with the
main package) are called Commands, while others are simply called Packages.The Main Package
So far, we’ve done everything inside ofpackage main. The main package should also contain a main() function which is a special function that acts as the entry point of an executable program.
Creating Custom Packages
Let’s create our own package calledcustom and add some source files to it such as code.go:
Imports and Exports
Just like other languages, Go also has a concept of imports and exports, but it’s very elegant.Any value (like a variable or function) can be exported and visible from other packages if they have been defined with an uppercase identifier.
custom package:
custom package.
Importing Packages
To import and access our custom package, let’s go to ourmain.go file and import it. We can refer to it using the module we had initialized in our go.mod file earlier:
Notice how the package name is the last name of the import path.
Multiple Imports
We can import multiple packages like this:Import Aliases
We can also alias our imports to avoid collisions:External Dependencies
In Go, we are not only limited to working with local packages. We can also install external packages usinggo install command as we saw earlier.
Let’s download a simple logging package github.com/rs/zerolog/log:
Make sure to check out the go doc of packages you install, which is usually located in the project’s readme file. go doc parses the source code and generates documentation in HTML format.
Folder Structure Conventions
Go doesn’t have a particular “folder structure” convention. Always try to organize your packages in a simple and intuitive way.Best Practices
- Keep related functionality together in the same package
- Use clear, descriptive package names
- Avoid deeply nested package hierarchies
- Group packages by functionality, not by type
- Keep package names short and concise
Key Takeaways
- Every Go file must declare a package at the top
- Uppercase identifiers are exported (public)
- Lowercase identifiers are package-private
- The
mainpackage is special and contains the entry point - Import paths are based on your module path
- External packages are managed through go modules