liveBook · Manning

Go mod init

As explained in Go in Practice, Second Edition

go mod init is a Go command that creates a new module definition with a specified module path.

Start a new Go project by running `go mod init [module path]` at the top level of its directory. The command creates `go.mod`, the file that records the module path and target Go version; it can also list dependencies added later. section 1.2.4

Choose the path and initialize the project:

  • Use a unique path if the code may be shared. A repository URL path such as `github.com/[USERNAME]/[REPO]` is a common choice. section 1.2.4 section 1.5
  • Run `go mod init github.com/[USERNAME]/[REPO]` in the project’s top-level directory, then add your Go files there or in subdirectories. section 1.2.4
  • As dependencies change, `go get` can add them and `go mod tidy` can clean up the dependency tree and `go.mod`. section 1.2.4

Initialize a small web application

In an empty application directory, run `go mod init hellogo`, then create `main.go` in that directory. The name `hellogo` works for a local example; choose a unique module path if you intend to share the code. You can then use `go run` to compile and execute the application during development. section 1.5

How Go in Practice, Second Edition covers it

How deep it goes
Shows the command, naming convention, and resulting go.mod file, but does not examine module-file syntax in detail.
Examples
Uses `go mod init hellogo` before creating a small HTTP server, alongside a repository-URL naming example.
What it assumes
Assumes a directory for the application and teaches module initialization from its first command.
What you can do after
Operate/configure it to create a Go module in a chosen project directory with an appropriate path.
How it connects
Links module paths and go.mod to dependency management with go get and go mod tidy.

Also explained in

Compare how 2 books explain go mod init →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.