In this tutorial, we aim to understand and create Go Modules. Modules in Go are collections of related Go packages that are released together. They are the foundation of package distribution in Go, and a major way of organizing and managing code dependencies in your Go projects.
By the end of this tutorial, you will learn:
Prerequisites:
- Basic knowledge of Go programming language.
- Go installed on your machine.
Modules are a way of organizing related Go code. Each module contains a collection of related go packages. A module is defined by a go.mod
file at the root of a directory tree. This go.mod
file defines the module path, which is the import path prefix for all packages within the module.
To create a new module, use the go mod init
command followed by the name of the module. This will create a new go.mod
file in your current directory. For example:
go mod init github.com/username/my-module
This will create a go.mod
file that looks like this:
module github.com/username/my-module
go 1.14
The go 1.14
line indicates the Go version used in this module.
When you import a package that is not in your module, Go will automatically add the latest version of that package to the go.mod
file as a dependency when you run go build
, go test
, or other commands that compile Go code.
Let's create a new Go module called hello
.
go mod init hello
This will create a go.mod
file:
module hello
go 1.14
Let's assume we have a file main.go
with the following code:
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
fmt.Println(cmp.Diff("Hello World", "Hello Go"))
}
When we run go build
or go run main.go
, Go will automatically add go-cmp
as a dependency in the go.mod
file:
module hello
go 1.14
require github.com/google/go-cmp v0.4.0
In this tutorial, we have learned the following:
The next step in your learning journey could be understanding how to upgrade or downgrade the versions of your dependencies, or how to replace one dependency with another.
cmp.Diff
function from the go-cmp
package.Solutions:
go mod init exercise
..go
file and import the package you want. Then run go build
.go-cmp
package:package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
fmt.Println(cmp.Diff("Hello World", "Hello Go"))
}
When you run this program, it will print the difference between the two strings.