Exclude Directives in go.mod
Learn how to use exclude directives in go.mod to prevent specific module versions from being used. Understand when to exclude versions and how it affects dependency resolution.
Detailed Explanation
Exclude Directives
The exclude directive prevents a specific version of a module from being used in your build. Go's dependency resolver will skip excluded versions and select the next available version instead.
Syntax
Single-line:
exclude github.com/example/lib v1.2.3
Block form:
exclude (
github.com/example/lib v1.2.3
github.com/example/lib v1.2.4
github.com/other/pkg v0.9.0
)
How Exclude Works
When Go encounters an excluded version during dependency resolution:
- It skips that specific version entirely
- It selects the next higher version that is not excluded
- If no higher version exists, the build fails
When to Use Exclude
Known-bad versions: A specific release has a critical bug
exclude github.com/lib/broken v2.1.0 // data corruption bug
Retracted versions: Before the retract directive existed, exclude was used for this purpose
Incompatible versions: A version that breaks your specific use case
exclude github.com/lib/api v3.0.0-rc1 // incompatible API changes
Exclude vs Replace
| Feature | exclude | replace |
|---|---|---|
| Purpose | Skip a version | Redirect to different source |
| Effect | Uses next available version | Uses specified replacement |
| Scope | Main module only | Main module only |
| Version needed | Specific version required | Can be version-less |
Limitations
- Only applies in the main module (ignored in dependencies)
- Cannot exclude a range of versions — each must be listed individually
- Does not prevent the excluded version from appearing in go.sum
- Rarely used in practice —
replaceandretractcover most cases
Formatting
The formatter groups exclude entries in a block and sorts them alphabetically:
exclude (
github.com/example/lib v1.2.3
github.com/example/lib v1.2.4
github.com/other/pkg v0.9.0
)
Use Case
Exclude directives are useful when a transitive dependency has a known-bad version and you cannot easily upgrade the direct dependency that pulls it in. Security teams use excludes to immediately block vulnerable versions. While less common than replace directives, excludes provide a targeted way to avoid specific problematic releases.