In this tutorial, we aim to help you understand how to work efficiently with Go modules and dependencies. Go modules are collections of Go packages stored in a file tree with a go.mod
file at its root. The go.mod
file defines the module’s module path, which is also the import path used for the root directory.
You will learn how to create, use, and manage Go modules & packages. We will also cover how to add and manage external dependencies.
To get the most out of this tutorial, you should have Go installed on your computer and a basic understanding of Go syntax.
To create a new module, use go mod init
followed by the module path. The module path is usually the repository location where your module code would live. For instance, if your code is hosted at github.com/myname/myrepo
, you would run:
go mod init github.com/myname/myrepo
This command will create a new go.mod
file in your current directory.
To add dependencies to your module, you simply import the package in your code, then run go build
, go test
, or any command that understands dependencies. This will automatically update your go.mod
file.
import "github.com/some/dependency"
Then run:
go build
To upgrade to the latest version of a dependency, use go get
followed by the package path:
go get github.com/some/dependency
To downgrade, append @version
to the command above:
go get github.com/some/dependency@v1.2.3
Unused dependencies can be removed by running go mod tidy
. This command will also add any missing dependencies required to build your code.
// main.go
package main
import (
"fmt"
"rsc.io/quote" // importing a dependency
)
func main() {
fmt.Println(quote.Hello())
}
Running go run main.go
will automatically add rsc.io/quote
to your go.mod
file, and the expected output will be:
Hello, world.
In this tutorial, we learned about Go modules and dependencies. We covered how to create a new module, how to add, upgrade, downgrade, and remove dependencies.
Create a new Go module and add a dependency of your choice. Print a value or call a function from the dependency.
Upgrade the dependency to the latest version and then downgrade it to a specific version.
Remove any unused dependencies from your module.
Remember, the more you practice, the better you'll get. So keep experimenting with different modules and dependencies to learn more about Go!