Initialize a module and read go.mod
Initialize a module and read go.mod
A module is a versioned collection of packages with a go.mod file at its root. The module directive names its import-path prefix. Run go mod init once in a new project; the go directive declares the minimum Go version and influences language semantics. A module can contain many packages.
Use a fresh directory for each example, create the listed files (labels are not file contents), and run the commands in a POSIX shell. Use Go 1.23+, local toolchain, and Python 3 only for the synthetic proxy examples. For isolation, set GOWORK=off, GOTOOLCHAIN=local, GOPROXY=off and GOSUMDB=off for these local labs only; use a fresh GOMODCACHE per lab. Proxy examples override GOPROXY to a local file URL. Do not copy disabled checksum settings to real projects.
--- main.go ---package main
import "fmt"
func main() { fmt.Println("hello module") }
--- Commands (shell, from project root) ---go mod init example.test/app 2>/dev/nullgo list -mgo run .go mod init writes go.mod; go list -m prints the main module path. Inspect the generated go directive, which depends on the installed toolchain. go run . builds the current main package. Do not initialize a new module in every package directory.
Expected output:
example.test/apphello moduleImport a package within the module
--- go.mod ---module example.test/app
go 1.23.0
--- main.go ---package main
import ( "example.test/app/label" "fmt")
func main() { fmt.Println(label.Name()) }
--- label/label.go ---package label
func Name() string { return "local package" }
--- Commands (shell, from project root) ---go list ./...go run .Both package paths start with the module path. No dependency download is needed. A real published module should use a path you control; example.test is reserved for these exercises.
Expected output:
example.test/appexample.test/app/labellocal packageTry it locally
Initialize example.test/shop and print its module path and a message shop.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Modules and workspaces 01: Initialize a module and read go.mod
Check the lesson objective before moving on.
Which file declares the module path?
What does go list -m show without arguments?