Learn The Go Programming Language — Packages
Code can be easily shared between programs using packages. Additionally, they make it easy for developers to share code.
The Go programming language allows us to define our own packages. Packages are groups of code that perform similar tasks. Formatting output is handled by the fmt package, numbers are handled by the math package, and strings are handled by the strings package.
The ability to reuse code between programs is one of the major reasons why packages exist. Consider moving code into packages if parts of it are shared between several programs.
Go tools look for package code in a directory called the workspace on your computer. As a default, the workspace is located in the current user’s home directory under the name go.
The workspace contains three subdirectories:
- bin — It holds compiled binary executable programs.
- pkg — It holds compiled binary package files.
- src — It holds the Go source code.
Each package’s code resides in a separate subdirectory in the src directory. As a convention, the subdirectory name should be the same as the package name.
There should be one or more source code files in each package directory. Filenames don’t matter, but they must end in .go.
A module consists of a collection of Go packages. A module consists of two files: go.mod and go.sum. Go.mod defines the module path and dependency requirements. Go.sum is an auto-generated dependencies lock file.
Modules allow us to define precise dependency requirements and design reproducible builds across multiple environments. A module cache stores third-party modules downloaded from their repositories. When applications are built, these dependencies are loaded from these copies. By default, the module cache is located in the go subdirectory of the home directory.
Go Module Commands
The go tool provides several commands that are related to modules.
- go mod init — initializes new module in the current directory
- go mod tidy — adds missing and removes unused modules
- go mod download — downloads modules to the local cache
- go mod vendor — makes vendored copy of dependencies
- go mod graph — prints module requirement graph
- go mod verify — verifies dependencies have expected content
- go mod why — explains why packages or modules are needed
Creating a new package
Please install Visual Studio Code, which is free to use, before we begin creating a new package. The Go extension for Visual Studio Code adds features like IntelliSense, navigation, symbol search, testing, debugging, and many more for Go development.
More details can be found on https://code.visualstudio.com/docs/languages/go
Create a folder named src within the go directory in your home directory.
With the go mod init command, let’s initialize the module.
// go mod init [module-path]
go mod init season.com
Module paths are used to import all packages of a module. It is common for developers to use the URL of the repository that hosts the source code as the module path.
The last step is to create a directory that holds our package code. By convention, a package’s directory should have the same name as the package itself. As our package will be named season, you should name the directory src/season accordingly.
Next, create a file named season.go within the season directory.
As with all of our Go source code files, this file begins with a package line. This code is now part of the season package.
We have capitalized the first letter of the function name, so it is exported.
Create a new subdirectory named main within the src subdirectory in your workspace directory. Within your new main directory, we need to create another source file. We will call it main.go.
This code starts with a package line, but because we intend this to be an executable one, we need to use the package name of the main. Next, we need to import the season package so we can use its functions.
In your terminal, run the command go run main.go to run the program.
go run .\main\main.go
Current Season is Autumn
Package naming conventions
Developers who use a package will need to type its name every time they call a function from it. There are a few rules that package names should follow in order to make that process as painless as possible:
- All package names should be lowercase.
- If the meaning of the name is fairly obvious, such as fmt, then it should be abbreviated.
- Ideally, it should be one word. Whenever two words are needed, they should not be separated by underscores, and the second word should not be capitalized such as strconv package.
- Names of imported packages can conflict with local variable names, so don’t choose a name that users will also want to use.
You must qualify the name of a function or variable exported from another package by typing the package name before it. You should not qualify the package name when accessing a function or variable that’s defined in the current package.
There are many packages that export constants named values that never change. A constant declaration is similar to a variable declaration, with a name, optional type, and value. However, the rules are slightly different.
- Const is used instead of var.
- As with variables, you can’t assign a value after the constant is declared.
- The := short variable declaration syntax is available for variables, but not for constants.
const MonthsInYear int = 12
The type will be inferred from the value being assigned, just as with variable declarations. Constants whose names begin with a capital letter are exported, and we can access them from other packages by qualifying their names.
Installing Program Executables
When we use “go run”, Go has to compile the program, as well as all the packages it depends on, before it can execute it. And it throws that compiled code away when it’s done.
The go install command also saves compiled binary versions of executable programs, but in a well-defined, easily accessible place, a bin directory in your Go workspace.
Changing workspaces with GOPATH
GOPATH is an environment variable that Go tools consult to find the location of your workspace. If your code is stored in a directory other than the default, you will need to configure the go tool to look in the right place. You can do that by setting the GOPATH environment variable.
- Within your user’s home directory, the workspace directory is named go by default.
- By setting the GOPATH environment variable, you can use another directory as your workspace.
- Within the workspace, Go uses three subdirectories: the bin directory contains compiled executable programs, the pkg directory contains compiled package code, and the src directory contains Go source code.
- The name of the package is determined by the package clauses at the top of the source code files. Package names should be the same as the names of the directories they reside in, except for the main package.
- All package names should be lowercase, and ideally, should contain one word.
- Only exported functions can be called from outside a package. If a function’s name begins with a capital letter, then it is exported.
- Constants refer to values that will never change.
- If you are installing a general package, or an executable program, the go install command compiles the package’s code and stores it in the pkg directory.