Modules with go mod
| go mod init | |
| go mod tidy | |
| Run inside a module | |
| Import your own package |
go mod init
A module is a project with a go.mod file that records the module path and the Go version.
Create a project folder, open it in the terminal, and initialize the module with a path that mirrors the future repository location.
go mod init example/hello
go: creating new go.mod: module example/hello
module example/hello
go 1.21
go mod tidy
The go mod tidy command adds missing requirements and removes unused ones, so go.mod always matches the actual imports.
Run it after adding or deleting dependencies, and commit the resulting go.mod and go.sum files with the project.
go mod tidy
A clean project prints nothing, which means there is nothing to fix.
Run inside a module
Inside a module, commands accept a package pattern instead of file names, and a single dot means the current folder.
package main
import "fmt"
func main() {
fmt.Println("Hello from a module")
}
go run .
Hello from a module
Import your own package
Larger programs split code into packages, where each folder holds one package and the import path extends the module path with the folder name.
Save the helper below as greet/greet.go and import it from main.go by the full path.
package greet
func Hello() string {
return "Hello from greet"
}
package main
import (
"example/hello/greet"
"fmt"
)
func main() {
fmt.Println(greet.Hello())
}
go run .
Hello from greet
Next: Variables
Article author: Arthur Isaev