Basic go.mod File Structure

Understand the fundamental structure of a go.mod file including module path, Go version, and require directives. Learn how Go modules organize dependencies in a simple, readable format.

Basic Structure

Detailed Explanation

The go.mod File Structure

Every Go module begins with a go.mod file at the root of the project directory. This file defines the module's identity and its dependencies. Understanding the structure is essential for any Go developer.

Required Elements

A minimal go.mod file contains two directives:

module github.com/example/myproject

go 1.22.0

The module directive declares the module path — the import path prefix for all packages in the module. This is typically the repository URL where the code is hosted.

The go directive specifies the minimum Go version required to build the module. Since Go 1.21, this also affects language semantics (e.g., loop variable scoping in Go 1.22).

Require Blocks

Dependencies are listed in require blocks:

require (
    github.com/gin-gonic/gin v1.9.1
    golang.org/x/text       v0.14.0
)

Each entry consists of a module path and a version. Go uses semantic versioning (semver) with the v prefix. The go mod tidy command automatically manages these entries.

Direct vs Indirect Dependencies

Go separates dependencies into two require blocks:

  • Direct dependencies — packages your code imports directly
  • Indirect dependencies — transitive dependencies required by your direct dependencies, marked with // indirect

File Conventions

  • Indentation uses tabs (not spaces)
  • Entries within a block are typically sorted alphabetically
  • Version numbers are aligned for readability
  • The file ends with a newline

Use Case

Understanding go.mod structure is fundamental for every Go developer. Whether you are starting a new project with `go mod init`, adding dependencies with `go get`, or reviewing dependency changes in pull requests, knowing the file format helps you work efficiently with the Go module system.

Try It — go.mod Formatter

Open full tool