Go Modules
A module is a collection of packages that belong together. The go.mod file records the module path.
Three Grouped Imports
A program in a module can use many packages at once. This one groups fmt, math, and strings.
package main
import (
"fmt"
"math"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("module"))
fmt.Println(math.Max(2, 9))
}Two Packages in One Program
FormatInt turns a number into text. The strings package then puts that text in capitals.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
text := strconv.FormatInt(255, 16)
fmt.Println(text)
fmt.Println(strings.ToUpper(text))
}Example
package main
import (
"fmt"
"strings"
)
func main() {
sentence := "go modules group packages"
words := strings.Fields(sentence)
fmt.Println("Words:", len(words))
}Key points
- Module: a collection of packages that belong together.
- Use go mod init with a module path to start a module.
- The command writes a file named go.mod in the project folder.
- The go.mod file records the module path and the Go version.
- Module path: the name that import paths in the module start with.
- One module can hold several packages, each in its own folder.
In this example, Fields splits the sentence into its words. The len call counts the words in the slice. The sentence has four words, so the printed count is 4.
Note
The single-file programs in this course run with no go.mod file.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does the command go mod init example.com/hello create?