Go Modules in Depth
A module is a collection of packages that belong together. A module gives its packages one path that their import paths start with.
A grouped import of three packages
One import block groups three packages. Itoa turns a whole number into text, and each package does one job in main.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
text := strconv.Itoa(42)
fmt.Println(text)
fmt.Println(strings.ToUpper("module"))
}Import paths name each package
The import path encoding/json has two parts, and its last part is the package name. Sort puts the words in order, and Marshal turns them into JSON text.
package main
import (
"encoding/json"
"fmt"
"slices"
"strings"
)
func main() {
words := []string{"banana", "fig", "kiwi"}
slices.Sort(words)
fmt.Println(strings.Join(words, ", "))
data, err := json.Marshal(words)
if err != nil {
fmt.Println("Could not build JSON")
return
}
fmt.Println(string(data))
}Example
package main
import (
"fmt"
"slices"
"strconv"
"strings"
)
func main() {
sentence := "go is fun and go is fast"
words := strings.Fields(sentence)
slices.Sort(words)
fmt.Println(strings.Join(words, " "))
fmt.Println("Words:", strconv.Itoa(len(words)))
}Key points
- One module gathers packages that belong together.
- The go.mod file is a text file that holds the facts of a module.
- The module line in go.mod gives the module path.
- The go line in go.mod names the Go version the module expects.
- A require line in go.mod names a module the code needs and the version it needs.
- A version is a label such as v1.2.3 that names one release of a module.
- Use go mod tidy to match the require lines in go.mod to the imports in the code.
In this example, Fields splits the sentence into seven words. Sort from the slices package puts the words in order. Join builds one line from the sorted words. Itoa turns the word count into text for the last print.
Note
The programs in this lesson run as single files, so they need no go.mod file.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does a require line in go.mod do?