`,
U+0060). Interpreted strings may contain escape sequences consisting of a
backslash (`\`, U+005C) followed by another character. An escaped quotation
mark (`\"`) does not terminate an interpreted string. The unquoted value
of an interpreted string is the sequence of characters between quotation
marks with each escape sequence replaced by the character following the
backslash (for example, `\"` is replaced by `"`, `\n` is replaced by `n`).
In contrast, the unquoted value of a raw string is simply the sequence of
characters between grave accents; backslashes have no special meaning within
raw strings.
Identifiers and strings are interchangeable in the `go.mod` grammar.
### Module paths and versions {#go-mod-file-ident}
Most identifiers and strings in a `go.mod` file are either module paths or
versions.
A module path must satisfy the following requirements:
* The path must consist of one or more path elements separated by slashes
(`/`, U+002F). It must not begin or end with a slash.
* Each path element is a non-empty string made of up ASCII letters, ASCII
digits, and limited ASCII punctuation (`-`, `.`, `_`, and `~`).
* A path element may not begin or end with a dot (`.`, U+002E).
* The element prefix up to the first dot must not be a reserved file name on
Windows, regardless of case (`CON`, `com1`, `NuL`, and so on).
* The element prefix up to the first dot must not end with a tilde followed by
one or more digits (like `EXAMPL~1.COM`).
If the module path appears in a `require` directive and is not replaced, or
if the module paths appears on the right side of a `replace` directive,
the `go` command may need to download modules with that path, and some
additional requirements must be satisfied.
* The leading path element (up to the first slash, if any), by convention a
domain name, must contain only lower-case ASCII letters, ASCII digits, dots
(`.`, U+002E), and dashes (`-`, U+002D); it must contain at least one dot and
cannot start with a dash.
* For a final path element of the form `/vN` where `N` looks numeric (ASCII
digits and dots), `N` must not begin with a leading zero, must not be `/v1`,
and must not contain any dots.
* For paths beginning with `gopkg.in/`, this requirement is replaced by a
requirement that the path follow the [gopkg.in](https://gopkg.in) service's
conventions.
Versions in `go.mod` files may be [canonical](#glos-canonical-version) or
non-canonical.
A canonical version starts with the letter `v`, followed by a semantic version
following the [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html)
specification. See [Versions](#versions) for more information.
Most other identifiers and strings may be used as non-canonical versions, though
there are some restrictions to avoid problems with file systems, repositories,
and [module proxies](#glos-module-proxy). Non-canonical versions are only
allowed in the main module's `go.mod` file. The `go` command will attempt to
replace each non-canonical version with an equivalent canonical version when it
automatically [updates](#go-mod-file-updates) the `go.mod` file.
In places where a module path is associated with a version (as in `require`,
`replace`, and `exclude` directives), the final path element must be consistent
with the version. See [Major version suffixes](#major-version-suffixes).
### Grammar {#go-mod-file-grammar}
`go.mod` syntax is specified below using Extended Backus-Naur Form (EBNF).
See the [Notation section in the Go Language Specification](/ref/spec#Notation)
for details on EBNF syntax.
```
GoMod = { Directive } .
Directive = ModuleDirective |
GoDirective |
ToolDirective |
IgnoreDirective |
RequireDirective |
ExcludeDirective |
ReplaceDirective |
RetractDirective .
```
Newlines, identifiers, and strings are denoted with `newline`, `ident`, and
`string`, respectively.
Module paths and versions are denoted with `ModulePath` and `Version`.
```
ModulePath = ident | string . /* see restrictions above */
Version = ident | string . /* see restrictions above */
```
### `module` directive {#go-mod-file-module}
A `module` directive defines the main module's [path](#glos-module-path). A
`go.mod` file must contain exactly one `module` directive.
```
ModuleDirective = "module" ( ModulePath | "(" newline ModulePath newline ")" ) newline .
```
Example:
```
module golang.org/x/net
```
#### Deprecation {#go-mod-file-module-deprecation}
A module can be marked as deprecated in a block of comments containing the
string `Deprecated:` (case-sensitive) at the beginning of a paragraph. The
deprecation message starts after the colon and runs to the end of the paragraph.
The comments may appear immediately before the `module` directive or afterward
on the same line.
Example:
```
// Deprecated: use example.com/mod/v2 instead.
module example.com/mod
```
Since Go 1.17, [`go list -m -u`](#go-list-m) checks for information on all
deprecated modules in the [build list](#glos-build-list). [`go get`](#go-get)
checks for deprecated modules needed to build packages named on the command
line.
When the `go` command retrieves deprecation information for a module, it loads
the `go.mod` file from the version matching the `@latest` [version
query](#version-queries) without considering [retractions](#go-mod-file-retract) or
[exclusions](#go-mod-file-exclude). The `go` command loads the list of
[retracted versions](#glos-retracted-version) from the same `go.mod` file.
To deprecate a module, an author may add a `// Deprecated:` comment and tag a
new release. The author may change or remove the deprecation message in a higher
release.
A deprecation applies to all minor versions of a module. Major versions higher
than `v2` are considered separate modules for this purpose, since their [major
version suffixes](#glos-major-version-suffix) give them distinct module paths.
Deprecation messages are intended to inform users that the module is no longer
supported and to provide migration instructions, for example, to the latest
major version. Individual minor and patch versions cannot be deprecated;
[`retract`](#go-mod-file-retract) may be more appropriate for that.
### `go` directive {#go-mod-file-go}
A `go` directive indicates that a module was written assuming the semantics of a
given version of Go. The version must be a valid [Go version](/doc/toolchain#version),
such as `1.14`, `1.21rc1`, or `1.23.0`.
The `go` directive sets the minimum version of Go required to use this module.
Before Go 1.21, the directive was advisory only; now it is a mandatory requirement:
Go toolchains refuse to use modules declaring newer Go versions.
The `go` directive is an input into selecting which Go toolchain to run.
See “[Go toolchains](/doc/toolchain)” for details.
The `go` directive affects use of new language features:
* For packages within the module, the compiler rejects use of language features
introduced after the version specified by the `go` directive. For example, if
a module has the directive `go 1.12`, its packages may not use numeric
literals like `1_000_000`, which were introduced in Go 1.13.
* If an older Go version builds one of the module's packages and encounters a
compile error, the error notes that the module was written for a newer Go
version. For example, suppose a module has `go 1.13` and a package uses the
numeric literal `1_000_000`. If that package is built with Go 1.12, the
compiler notes that the code is written for Go 1.13.
The `go` directive also affects the behavior of the `go` command:
* At `go 1.14` or higher, automatic [vendoring](#vendoring) may be enabled.
If the file `vendor/modules.txt` is present and consistent with `go.mod`,
there is no need to explicitly use the `-mod=vendor` flag.
* At `go 1.16` or higher, the `all` package pattern matches only packages
transitively imported by packages and tests in the [main
module](#glos-main-module). This is the same set of packages retained by
[`go mod vendor`](#go-mod-vendor) since modules were introduced. In lower
versions, `all` also includes tests of packages imported by packages in
the main module, tests of those packages, and so on.
* At `go 1.17` or higher:
* The `go.mod` file includes an explicit [`require`
directive](#go-mod-file-require) for each module that provides any package
transitively imported by a package or test in the main module. (At `go
1.16` and lower, an [indirect dependency](#glos-direct-dependency) is
included only if [minimal version selection](#minimal-version-selection)
would otherwise select a different version.) This extra information enables
[module graph pruning](#graph-pruning) and [lazy module
loading](#lazy-loading).
* Because there may be many more `// indirect` dependencies than in previous
`go` versions, indirect dependencies are recorded in a separate block
within the `go.mod` file.
* `go mod vendor` omits `go.mod` and `go.sum` files for vendored
dependencies. (That allows invocations of the `go` command within
subdirectories of `vendor` to identify the correct main module.)
* `go mod vendor` records the `go` version from each dependency's `go.mod`
file in `vendor/modules.txt`.
* At `go 1.21` or higher:
* The `go` line declares a required minimum version of Go to use with this module.
* The `go` line must be greater than or equal to the `go` line of all dependencies.
* The `go` command no longer attempts to maintain compatibility with the previous older version of Go.
* The `go` command is more careful about keeping checksums of `go.mod` files in the `go.sum` file.
A `go.mod` file may contain at most one `go` directive. Most commands will add a
`go` directive with the current Go version if one is not present.
If the `go` directive is missing, `go 1.16` is assumed.
```
GoDirective = "go" GoVersion newline .
GoVersion = string | ident . /* valid release version; see above */
```
Example:
```
go 1.23.0
```
### `toolchain` directive {#go-mod-file-toolchain}
A `toolchain` directive declares a suggested Go toolchain to use with a module.
The suggested Go toolchain's version cannot be less than the required Go version
declared in the `go` directive.
The `toolchain` directive
only has an effect when the module is the main module and the default toolchain's
version is less than the suggested toolchain's version.
For reproducibility, the `go` command writes its own toolchain name in a `toolchain` line any time
it is updating the `go` version in the `go.mod` file (usually during `go get`).
For details, see “[Go toolchains](/doc/toolchain)”.
```
ToolchainDirective = "toolchain" ToolchainName newline .
ToolchainName = string | ident . /* valid toolchain name; see “Go toolchains” */
```
Example:
```
toolchain go1.21.0
```
### `godebug` directive {#go-mod-file-godebug}
A `godebug` directive declares a single [GODEBUG setting](/doc/godebug)
to apply when this module is the main module.
There can be more than one such line, and they can be factored.
It is an error for the main module to name a GODEBUG key that does not exist.
The effect of `godebug key=value` is as if every main package being compiled
contained a source file that listed `//go:debug key=value`.
```
GodebugDirective = "godebug" ( GodebugSpec | "(" newline { GodebugSpec } ")" newline ) .
GodebugSpec = GodebugKey "=" GodebugValue newline.
GodebugKey = GodebugChar { GodebugChar }.
GodebugValue = GodebugChar { GodebugChar }.
GodebugChar = any non-space character except , " ` ' (comma and quotes).
```
Example:
```
godebug default=go1.21
godebug (
panicnil=1
asynctimerchan=0
)
```
### `require` directive {#go-mod-file-require}
A `require` directive declares a minimum required version of a given module
dependency. For each required module version, the `go` command loads the
`go.mod` file for that version and incorporates the requirements from that
file. Once all requirements have been loaded, the `go` command resolves them
using [minimal version selection (MVS)](#minimal-version-selection) to produce
the [build list](#glos-build-list).
The `go` command automatically adds `// indirect` comments for some
requirements. An `// indirect` comment indicates that no package from the
required module is directly imported by any package in the [main
module](#glos-main-module).
If the [`go` directive](#go-mod-file-go) specifies `go 1.16` or lower, the `go`
command adds an indirect requirement when the selected version of a module is
higher than what is already implied (transitively) by the main module's other
dependencies. That may occur because of an explicit upgrade (`go get -u ./...`),
removal of some other dependency that previously imposed the requirement (`go
mod tidy`), or a dependency that imports a package without a corresponding
requirement in its own `go.mod` file (such as a dependency that lacks a `go.mod`
file altogether).
At `go 1.17` and above, the `go` command adds an indirect requirement for each
module that provides any package imported (even
[indirectly](#glos-indirect-dependency)) by a package or test in the main module
or passed as an argument to `go get`. These more comprehensive requirements
enable [module graph pruning](#graph-pruning) and [lazy module
loading](#lazy-loading).
```
RequireDirective = "require" ( RequireSpec | "(" newline { RequireSpec } ")" newline ) .
RequireSpec = ModulePath Version newline .
```
Example:
```
require golang.org/x/net v1.2.3
require (
golang.org/x/crypto v1.4.5 // indirect
golang.org/x/text v1.6.7
)
```
### `tool` directive {#go-mod-file-tool}
Since Go 1.24, a `tool` directive adds a package as a dependency of the current module. It also
makes it available to run with `go tool` when the current working directory is
within this module, or within a workspace that contains this module.
If the tool package is not in the current module, a `require`
directive must be present that specifies the version of the tool to use.
The `tool` meta-pattern resolves to the list of tools defined in the current module's
`go.mod`, or in workspace mode to the union of all tools defined in all modules in the
workspace.
```
ToolDirective = "tool" ( ToolSpec | "(" newline { ToolSpec } ")" newline ) .
ToolSpec = ModulePath newline .
```
Example:
```
tool golang.org/x/tools/cmd/stringer
tool (
example.com/module/cmd/a
example.com/module/cmd/b
)
```
### `ignore` directive {#go-mod-file-ignore}
An `ignore` directive will cause the go command ignore the slash-separated
directory paths, and any files or directories recursively contained in them,
when matching package patterns.
If the path starts with `./`, the path is interpreted relative to the
module root directory, and that directory and any directories or files
recursively contained in it will be ignored when matching package patterns.
Otherwise, any directories with the path at any depth in the module, and
any directories or files recursively contained in them will be ignored.
```
IgnoreDirective = "ignore" ( IgnoreSpec | "(" newline { IgnoreSpec } ")" newline ) .
IgnoreSpec = RelativeFilePath newline .
RelativeFilePath = /* slash-separated relative file path */ .
```
Example
```
ignore ./node_modules
ignore (
static
content/html
./third_party/javascript
)
```
### `exclude` directive {#go-mod-file-exclude}
An `exclude` directive prevents a module version from being loaded by the `go`
command.
Since Go 1.16, if a version referenced by a `require` directive in any `go.mod`
file is excluded by an `exclude` directive in the main module's `go.mod` file,
the requirement is ignored. This may cause commands like [`go get`](#go-get)
and [`go mod tidy`](#go-mod-tidy) to add new requirements on higher versions
to `go.mod`, with an `// indirect` comment if appropriate.
Before Go 1.16, if an excluded version was referenced by a `require` directive,
the `go` command listed available versions for the module (as shown with [`go
list -m -versions`](#go-list-m)) and loaded the next higher non-excluded version
instead. This could result in non-deterministic version selection, since the
next higher version could change over time. Both release and pre-release
versions were considered for this purpose, but pseudo-versions were not. If
there were no higher versions, the `go` command reported an error.
`exclude` directives only apply in the main module's `go.mod` file and are
ignored in other modules. See [Minimal version
selection](#minimal-version-selection) for details.
```
ExcludeDirective = "exclude" ( ExcludeSpec | "(" newline { ExcludeSpec } ")" newline ) .
ExcludeSpec = ModulePath Version newline .
```
Example:
```
exclude golang.org/x/net v1.2.3
exclude (
golang.org/x/crypto v1.4.5
golang.org/x/text v1.6.7
)
```
### `replace` directive {#go-mod-file-replace}
A `replace` directive replaces the contents of a specific version of a module,
or all versions of a module, with contents found elsewhere. The replacement
may be specified with either another module path and version, or a
platform-specific file path.
If a version is present on the left side of the arrow (`=>`), only that specific
version of the module is replaced; other versions will be accessed normally.
If the left version is omitted, all versions of the module are replaced.
If the path on the right side of the arrow is an absolute or relative path
(beginning with `./` or `../`), it is interpreted as the local file path to the
replacement module root directory, which must contain a `go.mod` file. The
replacement version must be omitted in this case.
If the path on the right side is not a local path, it must be a valid module
path. In this case, a version is required. The same module version must not
also appear in the build list.
Regardless of whether a replacement is specified with a local path or module
path, if the replacement module has a `go.mod` file, its `module` directive
must match the module path it replaces.
`replace` directives only apply in the main module's `go.mod` file
and are ignored in other modules. See [Minimal version
selection](#minimal-version-selection) for details.
If there are multiple main modules, all main modules' `go.mod`
files apply. Conflicting `replace` directives across main
modules are disallowed, and must be removed or overridden in
a [replace in the `go.work file`](#go-work-file-replace).
Note that a `replace` directive alone does not add a module to the [module
graph](#glos-module-graph). A [`require` directive](#go-mod-file-require) that
refers to a replaced module version is also needed, either in the main module's
`go.mod` file or a dependency's `go.mod` file. A `replace` directive has no
effect if the module version on the left side is not required.
```
ReplaceDirective = "replace" ( ReplaceSpec | "(" newline { ReplaceSpec } ")" newline ) .
ReplaceSpec = ModulePath [ Version ] "=>" FilePath newline
| ModulePath [ Version ] "=>" ModulePath Version newline .
FilePath = /* platform-specific relative or absolute file path */
```
Example:
```
replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
replace (
golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
golang.org/x/net => example.com/fork/net v1.4.5
golang.org/x/net v1.2.3 => ./fork/net
golang.org/x/net => ./fork/net
)
```
### `retract` directive {#go-mod-file-retract}
A `retract` directive indicates that a version or range of versions of the
module defined by `go.mod` should not be depended upon. A `retract` directive is
useful when a version was published prematurely or a severe problem was
discovered after the version was published. Retracted versions should remain
available in version control repositories and on [module
proxies](#glos-module-proxy) to ensure that builds that depend on them are not
broken. The word *retract* is borrowed from academic literature: a retracted
research paper is still available, but it has problems and should not be the
basis of future work.
When a module version is retracted, users will not upgrade to it automatically
using [`go get`](#go-get), [`go mod tidy`](#go-mod-tidy), or other
commands. Builds that depend on retracted versions should continue to work, but
users will be notified of retractions when they check for updates with [`go list
-m -u`](#go-list-m) or update a related module with [`go get`](#go-get).
To retract a version, a module author should add a `retract` directive to
`go.mod`, then publish a new version containing that directive. The new version
must be higher than other release or pre-release versions; that is, the
`@latest` [version query](#version-queries) should resolve to the new version
before retractions are considered. The `go` command loads and applies
retractions from the version shown by `go list -m -retracted $modpath@latest`
(where `$modpath` is the module path).
Retracted versions are hidden from the version list printed by [`go list -m
-versions`](#go-list-m) unless the `-retracted` flag is used. Retracted
versions are excluded when resolving version queries like `@>=v1.2.3` or
`@latest`.
A version containing retractions may retract itself. If the highest release
or pre-release version of a module retracts itself, the `@latest` query
resolves to a lower version after retracted versions are excluded.
As an example, consider a case where the author of module `example.com/m`
publishes version `v1.0.0` accidentally. To prevent users from upgrading to
`v1.0.0`, the author can add two `retract` directives to `go.mod`, then tag
`v1.0.1` with the retractions.
```
retract (
v1.0.0 // Published accidentally.
v1.0.1 // Contains retractions only.
)
```
When a user runs `go get example.com/m@latest`, the `go` command reads
retractions from `v1.0.1`, which is now the highest version. Both `v1.0.0` and
`v1.0.1` are retracted, so the `go` command will upgrade (or downgrade!) to
the next highest version, perhaps `v0.9.5`.
`retract` directives may be written with either a single version (like `v1.0.0`)
or with a closed interval of versions with an upper and lower bound, delimited by
`[` and `]` (like `[v1.1.0, v1.2.0]`). A single version is equivalent to an
interval where the upper and lower bound are the same. Like other directives,
multiple `retract` directives may be grouped together in a block delimited by
`(` at the end of a line and `)` on its own line.
Each `retract` directive should have a comment explaining the rationale for the
retraction, though this is not mandatory. The `go` command may display rationale
comments in warnings about retracted versions and in `go list` output. A
rationale comment may be written immediately above a `retract` directive
(without a blank line in between) or afterward on the same line. If a comment
appears above a block, it applies to all `retract` directives within the block
that don't have their own comments. A rationale comment may span multiple lines.
```
RetractDirective = "retract" ( RetractSpec | "(" newline { RetractSpec } ")" newline ) .
RetractSpec = ( Version | "[" Version "," Version "]" ) newline .
```
Examples:
* Retracting all versions between `v1.0.0` and `v1.9.9`:
```
retract v1.0.0
retract [v1.0.0, v1.9.9]
retract (
v1.0.0
[v1.0.0, v1.9.9]
)
```
* Returning to unversioned after prematurely released a version `v1.0.0`:
```
retract [v0.0.0, v1.0.1] // assuming v1.0.1 contains this retraction.
```
* Wiping out a module including all pseudo-versions and tagged versions:
```
retract [v0.0.0-0, v0.15.2] // assuming v0.15.2 contains this retraction.
```
The `retract` directive was added in Go 1.16. Go 1.15 and lower will report an
error if a `retract` directive is written in the [main
module's](#glos-main-module) `go.mod` file and will ignore `retract` directives
in `go.mod` files of dependencies.
### Automatic updates {#go-mod-file-updates}
Most commands report an error if `go.mod` is missing information or doesn't
accurately reflect reality. The [`go get`](#go-get) and
[`go mod tidy`](#go-mod-tidy) commands may be used to fix most of these
problems. Additionally, the `-mod=mod` flag may be used with most module-aware
commands (`go build`, `go test`, and so on) to instruct the `go` command to
fix problems in `go.mod` and `go.sum` automatically.
For example, consider this `go.mod` file:
```
module example.com/M
go 1.23.0
require (
example.com/A v1
example.com/B v1.0.0
example.com/C v1.0.0
example.com/D v1.2.3
example.com/E dev
)
exclude example.com/D v1.2.3
```
The update triggered with `-mod=mod` rewrites non-canonical version identifiers
to [canonical](#glos-canonical-version) semver form, so `example.com/A`'s `v1`
becomes `v1.0.0`, and `example.com/E`'s `dev` becomes the pseudo-version for the
latest commit on the `dev` branch, perhaps `v0.0.0-20180523231146-b3f5c0f6e5f1`.
The update modifies requirements to respect exclusions, so the requirement on
the excluded `example.com/D v1.2.3` is updated to use the next available version
of `example.com/D`, perhaps `v1.2.4` or `v1.3.0`.
The update removes redundant or misleading requirements. For example, if
`example.com/A v1.0.0` itself requires `example.com/B v1.2.0` and `example.com/C
v1.0.0`, then `go.mod`'s requirement of `example.com/B v1.0.0` is misleading
(superseded by `example.com/A`'s need for `v1.2.0`), and its requirement of
`example.com/C v1.0.0` is redundant (implied by `example.com/A`'s need for the
same version), so both will be removed. If the main module contains packages
that directly import packages from `example.com/B` or `example.com/C`, then the
requirements will be kept but updated to the actual versions being used.
Finally, the update reformats the `go.mod` in a canonical formatting, so
that future mechanical changes will result in minimal diffs. The `go` command
will not update `go.mod` if only formatting changes are needed.
Because the module graph defines the meaning of import statements, any commands
that load packages also use `go.mod` and can therefore update it, including
`go build`, `go get`, `go install`, `go list`, `go test`, `go mod tidy`.
In Go 1.15 and lower, the `-mod=mod` flag was enabled by default, so updates
were performed automatically. Since Go 1.16, the `go` command acts as
if `-mod=readonly` were set instead: if any changes to `go.mod` are needed,
the `go` command reports an error and suggests a fix.
## Minimal version selection (MVS) {#minimal-version-selection}
Go uses an algorithm called Minimal version selection (MVS) to select
a set of module versions to use when building packages. MVS is described in
detail in [Minimal Version Selection](https://research.swtch.com/vgo-mvs) by
Russ Cox.
Conceptually, MVS operates on a directed graph of modules, specified with
[`go.mod` files](#glos-go-mod-file). Each vertex in the graph represents a
module version. Each edge represents a minimum required version of a dependency,
specified using a [`require`](#go-mod-file-require)
directive. The graph may be modified by [`exclude`](#go-mod-file-exclude)
and [`replace`](#go-mod-file-replace) directives in the `go.mod` file(s) of the main
module(s) and by [`replace`](#go-work-file-replace) directives in the `go.work` file.
MVS produces the [build list](#glos-build-list) as output, the list of module
versions used for a build.
MVS starts at the main modules (special vertices in the graph that have no
version) and traverses the graph, tracking the highest required version of each
module. At the end of the traversal, the highest required versions comprise the
build list: they are the minimum versions that satisfy all requirements.
The build list may be inspected with the command [`go list -m
all`](#go-list-m). Unlike other dependency management systems, the build list is
not saved in a "lock" file. MVS is deterministic, and the build list doesn't
change when new versions of dependencies are released, so MVS is used to compute
it at the beginning of every module-aware command.
Consider the example in the diagram below. The main module requires module A
at version 1.2 or higher and module B at version 1.2 or higher. A 1.2 and B 1.2
require C 1.3 and C 1.4, respectively. C 1.3 and C 1.4 both require D 1.2.

MVS visits and loads the `go.mod` file for each of the module versions
highlighted in blue. At the end of the graph traversal, MVS returns a build list
containing the bolded versions: A 1.2, B 1.2, C 1.4, and D 1.2. Note that higher
versions of B and D are available but MVS does not select them, since nothing
requires them.
### Replacement {#mvs-replace}
The content of a module (including its `go.mod` file) may be replaced using a
[`replace` directive](#go-mod-file-replace) in a main module's `go.mod` file
or a workspace's `go.work` file. A `replace` directive may apply to a specific
version of a module or to all versions of a module.
Replacements change the module graph, since a replacement module may have
different dependencies than replaced versions.
Consider the example below, where C 1.4 has been replaced with R. R depends on D
1.3 instead of D 1.2, so MVS returns a build list containing A 1.2, B 1.2, C 1.4
(replaced with R), and D 1.3.

### Exclusion {#mvs-exclude}
A module may also be excluded at specific versions using an [`exclude`
directive](#go-mod-file-exclude) in the main module's `go.mod` file.
Exclusions also change the module graph. When a version is excluded, it is
removed from the module graph, and requirements on it are redirected to the
next higher version.
Consider the example below. C 1.3 has been excluded. MVS will act as if A 1.2
required C 1.4 (the next higher version) instead of C 1.3.

### Upgrades {#mvs-upgrade}
The [`go get`](#go-get) command may be used to upgrade a set of modules. To
perform an upgrade, the `go` command changes the module graph before running MVS
by adding edges from visited versions to upgraded versions.
Consider the example below. Module B may be upgraded from 1.2 to 1.3, C may be
upgraded from 1.3 to 1.4, and D may be upgraded from 1.2 to 1.3.

Upgrades (and downgrades) may add or remove indirect dependencies. In this case,
E 1.1 and F 1.1 appear in the build list after the upgrade, since E 1.1 is
required by B 1.3.
To preserve upgrades, the `go` command updates the requirements in `go.mod`. It
will change the requirement on B to version 1.3. It will also add requirements
on C 1.4 and D 1.3 with `// indirect` comments, since those versions would not
be selected otherwise.
### Downgrade {#mvs-downgrade}
The [`go get`](#go-get) command may also be used to downgrade a set of
modules. To perform a downgrade, the `go` command changes the module graph by
removing versions above the downgraded versions. It also removes versions of
other modules that depend on removed versions, since they may not be compatible
with the downgraded versions of their dependencies. If the main module requires
a module version removed by downgrading, the requirement is changed to a
previous version that has not been removed. If no previous version is available,
the requirement is dropped.
Consider the example below. Suppose that a problem was found with C 1.4, so we
downgrade to C 1.3. C 1.4 is removed from the module graph. B 1.2 is also
removed, since it requires C 1.4 or higher. The main module's requirement on B
is changed to 1.1.

[`go get`](#go-get) can also remove dependencies entirely, using an `@none`
suffix after an argument. This works similarly to a downgrade. All versions
of the named module are removed from the module graph.
## Module graph pruning {#graph-pruning}
If the main module is at `go 1.17` or higher, the [module
graph](#glos-module-graph) used for [minimal version
selection](#minimal-version-selection) includes only the _immediate_
requirements for each module dependency that specifies `go 1.17` or higher in
its own `go.mod` file, unless that version of the module is also (transitively)
required by some _other_ dependency at `go 1.16` or below. (The _transitive_
dependencies of `go 1.17` dependencies are _pruned out_ of the module graph.)
Since a `go 1.17` `go.mod` file includes a [require
directive](#go-mod-file-require) for every dependency needed to build any
package or test in that module, the pruned module graph includes all of the
dependencies needed to `go build` or `go test` the packages in any dependency
explicitly required by the [main module](#glos-main-module). A module that is
_not_ needed to build any package or test in a given module cannot affect the
run-time behavior of its packages, so the dependencies that are pruned out of
the module graph would only cause interference between otherwise-unrelated
modules.
Modules whose requirements have been pruned out still appear in the module graph
and are still reported by `go list -m all`: their [selected
versions](#glos-selected-version) are known and well-defined, and packages can
be loaded from those modules (for example, as transitive dependencies of tests
loaded from other modules). However, since the `go` command cannot easily
identify which dependencies of these modules are satisfied, the arguments to `go
build` and `go test` cannot include packages from modules whose requirements
have been pruned out. [`go get`](#go-get) promotes the module containing each
named package to an explicit dependency, allowing `go build` or `go test` to be
invoked on that package.
Because Go 1.16 and earlier did not support module graph pruning, the full
transitive closure of dependencies — including transitive `go 1.17`
dependencies — is still included for each module that specifies `go 1.16` or
lower. (At `go 1.16` and below, the `go.mod` file includes only
[direct dependencies](#glos-direct-dependency), so a much larger graph must be
loaded to ensure that all indirect dependencies are included.)
The [`go.sum` file](#go-sum-files) recorded by [`go mod tidy`](#go-mod-tidy) for
a module by default includes checksums needed by the Go version _one below_ the
version specified in its [`go` directive](#go-mod-file-go). So a `go 1.17`
module includes checksums needed for the full module graph loaded by Go 1.16,
but a `go 1.18` module will include only the checksums needed for the pruned
module graph loaded by Go 1.17. The `-compat` flag can be used to override the
default version (for example, to prune the `go.sum` file more aggressively in a
`go 1.17` module).
See [the design document](https://go.googlesource.com/proposal/+/master/design/36460-lazy-module-loading.md) for more detail.
### Lazy module loading {#lazy-loading}
The more comprehensive requirements added for module graph pruning also enable
another optimization when working within a module. If the main module is at
`go 1.17` or higher, the `go` command avoids loading the complete module graph
until (and unless) it is needed. Instead, it loads only the main module's
`go.mod` file, then attempts to load the packages to be built using only those
requirements. If a package to be imported (for example, a dependency of a test
for a package outside the main module) is not found among those requirements,
then the rest of the module graph is loaded on demand.
If all imported packages can be found without loading the module graph, the
`go` command then loads the `go.mod` files for _only_ the modules containing
those packages, and their requirements are checked against the requirements of
the main module to ensure that they are locally consistent. (Inconsistencies can
arise due to version-control merges, hand-edits, and changes in modules that
have been [replaced](#go-mod-file-replace) using local filesystem paths.)
## Workspaces {#workspaces}
A workspace is a collection of modules on disk that are used as
the main modules when running [minimal version selection (MVS)](#minimal-version-selection).
A workspace can be declared in a [`go.work` file](#go-work-file) that specifies
relative paths to the module directories of each of the modules in the workspace.
When no `go.work` file exists, the workspace consists of the single module
containing the current directory.
Most `go` subcommands that work with modules
operate on the set of modules determined by the current workspace.
`go mod init`, `go mod why`, `go mod edit`, `go mod tidy`, `go mod vendor`,
and `go get` always operate on a single main module.
A command determines whether it is in a workspace context by first examining
the `GOWORK` environment variable. If `GOWORK` is set to `off`, the command will be
in a single-module context. If it is empty or not provided, the command
will search the current working directory, and then successive parent directories,
for a file `go.work`. If a file is found, the command will operate in the
workspace it defines; otherwise, the workspace will include only the module
containing the working directory.
If `GOWORK` names a path to an existing file that ends in .work,
workspace mode will be enabled. Any other value is an error. You can use the
`go env GOWORK` command to determine which `go.work` file the `go` command
is using. `go env GOWORK` will be empty if the `go` command is not in workspace
mode.
### `go.work` files {#go-work-file}
A workspace is defined by a UTF-8 encoded text file named `go.work`. The
`go.work` file is line oriented. Each line holds a single directive, made up of
a keyword followed by arguments. For example:
```
go 1.23.0
use ./my/first/thing
use ./my/second/thing
replace example.com/bad/thing v1.4.5 => example.com/good/thing v1.4.5
```
As in `go.mod` files, a leading keyword can be factored out of adjacent lines
to create a block.
```
use (
./my/first/thing
./my/second/thing
)
```
The `go` command provides several subcommands for manipulating `go.work` files.
[`go work init`](#go-work-init) creates new `go.work` files. [`go work use`](#go-work-use) adds module directories to
the `go.work` file. [`go work edit`](#go-work-edit) performs low-level
edits. The
[`golang.org/x/mod/modfile`](https://pkg.go.dev/golang.org/x/mod/modfile?tab=doc)
package can be used by Go programs to make the same changes programmatically.
The go command will maintain a `go.work.sum` file that keeps track of hashes used by the workspace
that are not in collective workspace modules' go.sum files.
It is generally inadvisable to commit go.work files into version control
systems, for two reasons:
* A checked-in `go.work` file might override a developer's own `go.work` file
from a parent directory, causing confusion when their `use` directives don't
apply.
* A checked-in `go.work` file may cause a continuous integration (CI) system to
select and thus test the wrong versions of a module's dependencies. CI systems
should generally not be allowed to use the `go.work` file so that they can test
the behavior of the module as it would be used when required by other modules,
where a `go.work` file within the module has no effect.
That said, there are some cases where committing a `go.work` file makes sense.
For example, when the modules in a repository are developed exclusively with
each other but not together with external modules, there may not be a reason the
developer would want to use a different combination of modules in a workspace.
In that case, the module author should ensure the individual modules are tested
and released properly.
### Lexical elements {#go-work-file-lexical}
Lexical elements in `go.work` files are defined in exactly the same way [as for
`go.mod files`](#go-mod-file-lexical).
### Grammar {#go-work-file-grammar}
`go.work` syntax is specified below using Extended Backus-Naur Form (EBNF).
See the [Notation section in the Go Language Specification](/ref/spec#Notation)
for details on EBNF syntax.
```
GoWork = { Directive } .
Directive = GoDirective |
ToolchainDirective |
UseDirective |
ReplaceDirective .
```
Newlines, identifiers, and strings are denoted with `newline`, `ident`, and
`string`, respectively.
Module paths and versions are denoted with `ModulePath` and `Version`.
Module paths and versions are specified in exactly the same way [as for
`go.mod files`](#go-mod-file-lexical).
```
ModulePath = ident | string . /* see restrictions above */
Version = ident | string . /* see restrictions above */
```
### `go` directive {#go-work-file-go}
A `go` directive is required in a valid `go.work` file. The version must
be a valid Go release version: a positive
integer followed by a dot and a non-negative integer (for example, `1.18`,
`1.19`).
The `go` directive indicates the go toolchain version with which the
`go.work` file is intended to work. If changes are made to the `go.work`
file format, future versions of the toolchain will interpret the file
according to its indicated version.
A `go.work` file may contain at most one `go` directive.
```
GoDirective = "go" GoVersion newline .
GoVersion = string | ident . /* valid release version; see above */
```
Example:
```
go 1.23.0
```
### `toolchain` directive {#go-work-file-toolchain}
A `toolchain` directive declares a suggested Go toolchain to use in a workspace.
It only has an effect when the default toolchain
is older than the suggested toolchain.
For details, see “[Go toolchains](/doc/toolchain)”.
```
ToolchainDirective = "toolchain" ToolchainName newline .
ToolchainName = string | ident . /* valid toolchain name; see “Go toolchains” */
```
Example:
```
toolchain go1.21.0
```
### `godebug` directive {#go-work-file-godebug}
A `godebug` directive declares a single [GODEBUG setting](/doc/godebug)
to apply when working in this workspace.
The syntax and effect is the same as the [`go.mod` file's `godebug` directive](#go-mod-file-godebug).
When a workspace is in use, `godebug` directives in `go.mod` files are ignored.
### `use` directive {#go-work-file-use}
A `use` adds a module on disk to the set of main modules in a workspace.
Its argument is a relative path to the directory containing the module's
`go.mod` file. A `use` directive does not add modules contained in
subdirectories of its argument directory. Those modules may be added by
the directory containing their `go.mod` file in separate `use` directives.
```
UseDirective = "use" ( UseSpec | "(" newline { UseSpec } ")" newline ) .
UseSpec = FilePath newline .
FilePath = /* platform-specific relative or absolute file path */
```
Example:
```
use ./mymod // example.com/mymod
use (
../othermod
./subdir/thirdmod
)
```
### `replace` directive {#go-work-file-replace}
Similar to a `replace` directive in a `go.mod` file, a `replace` directive in
a `go.work` file replaces the contents of a specific version of a module,
or all versions of a module, with contents found elsewhere. A wildcard replace
in `go.work` overrides a version-specific `replace` in a `go.mod` file.
`replace` directives in `go.work` files override any replaces of the same
module or module version in workspace modules.
```
ReplaceDirective = "replace" ( ReplaceSpec | "(" newline { ReplaceSpec } ")" newline ) .
ReplaceSpec = ModulePath [ Version ] "=>" FilePath newline
| ModulePath [ Version ] "=>" ModulePath Version newline .
FilePath = /* platform-specific relative or absolute file path */
```
Example:
```
replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
replace (
golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
golang.org/x/net => example.com/fork/net v1.4.5
golang.org/x/net v1.2.3 => ./fork/net
golang.org/x/net => ./fork/net
)
```
## Compatibility with non-module repositories {#non-module-compat}
To ensure a smooth transition from `GOPATH` to modules, the `go` command can
download and build packages in module-aware mode from repositories that have not
migrated to modules by adding a [`go.mod` file](#glos-go-mod-file).
When the `go` command downloads a module at a given version [directly](#vcs)
from a repository, it looks up a repository URL for the module path, maps the
version to a revision within the repository, then extracts an archive of the
repository at that revision. If the [module's path](#glos-module-path) is equal
to the [repository root path](#glos-repository-root-path), and the repository
root directory does not contain a `go.mod` file, the `go` command synthesizes a
`go.mod` file in the module cache that contains a [`module`
directive](#go-mod-file-module) and nothing else. Since synthetic `go.mod` files
do not contain [`require` directives](#go-mod-file-require) for their
dependencies, other modules that depend on them may need additional `require`
directives (with `// indirect` comments) to ensure each dependency is fetched at
the same version on every build.
When the `go` command downloads a module from a
[proxy](#communicating-with-proxies), it downloads the `go.mod` file separately
from the rest of the module content. The proxy is expected to serve a synthetic
`go.mod` file if the original module didn't have one.
### `+incompatible` versions {#incompatible-versions}
A module released at major version 2 or higher must have a matching [major
version suffix](#major-version-suffixes) on its module path. For example, if a
module is released at `v2.0.0`, its path must have a `/v2` suffix. This allows
the `go` command to treat multiple major versions of a project as distinct
modules, even if they're developed in the same repository.
The major version suffix requirement was introduced when module support was
added to the `go` command, and many repositories had already tagged releases
with major version `2` or higher before that. To maintain compatibility with
these repositories, the `go` command adds an `+incompatible` suffix to versions
with major version 2 or higher without a `go.mod` file. `+incompatible`
indicates that a version is part of the same module as versions with lower major
version numbers; consequently, the `go` command may automatically upgrade to
higher `+incompatible` versions even though it may break the build.
Consider the example requirement below:
```
require example.com/m v4.1.2+incompatible
```
The version `v4.1.2+incompatible` refers to the [semantic version
tag](#glos-semantic-version-tag) `v4.1.2` in the repository that provides the
module `example.com/m`. The module must be in the repository root directory
(that is, the [repository root path](#glos-module-path) must also be
`example.com/m`), and a `go.mod` file must not be present. The module may have
versions with lower major version numbers like `v1.5.2`, and the `go` command
may upgrade automatically to `v4.1.2+incompatible` from those versions (see
[minimal version selection (MVS)](#minimal-version-selection) for information
on how upgrades work).
A repository that migrates to modules after version `v2.0.0` is tagged should
usually release a new major version. In the example above, the author should
create a module with the path `example.com/m/v5` and should release version
`v5.0.0`. The author should also update imports of packages in the module to use
the prefix `example.com/m/v5` instead of `example.com/m`. See [Go Modules: v2
and Beyond](/blog/v2-go-modules) for a more detailed example.
Note that the `+incompatible` suffix should not appear on a tag in a repository;
a tag like `v4.1.2+incompatible` will be ignored. The suffix only appears in
versions used by the `go` command. See [Mapping versions to
commits](#vcs-version) for details on the distinction between versions and tags.
Note also that the `+incompatible` suffix may appear on
[pseudo-versions](#glos-pseudo-version). For example,
`v2.0.1-20200722182040-012345abcdef+incompatible` may be a valid pseudo-version.
### Minimal module compatibility {#minimal-module-compatibility}
A module released at major version 2 or higher is required to have a [major
version suffix](#glos-major-version-suffix) on its [module
path](#glos-module-path). The module may or may not be developed in a [major
version subdirectory](#glos-major-version-subdirectory) within its repository.
This has implications for packages that import packages within the module when
building `GOPATH` mode.
Normally in `GOPATH` mode, a package is stored in a directory matching its
[repository's root path](#glos-repository-root-path) joined with its directory
within the repository. For example, a package in the repository with root path
`example.com/repo` in the subdirectory `sub` would be stored in
`$GOPATH/src/example.com/repo/sub` and would be imported as
`example.com/repo/sub`.
For a module with a major version suffix, one might expect to find the package
`example.com/repo/v2/sub` in the directory
`$GOPATH/src/example.com/repo/v2/sub`. This would require the module to be
developed in the `v2` subdirectory of its repository. The `go` command supports
this but does not require it (see [Mapping versions to commits](#vcs-version)).
If a module is *not* developed in a major version subdirectory, then its
directory in `GOPATH` will not contain the major version suffix, and its
packages may be imported without the major version suffix. In the example above,
the package would be found in the directory `$GOPATH/src/example.com/repo/sub`
and would be imported as `example.com/repo/sub`.
This creates a problem for packages intended to be built in both module mode
and `GOPATH` mode: module mode requires a suffix, while `GOPATH` mode does not.
To fix this, minimal module compatibility was added in Go 1.11 and
was backported to Go 1.9.7 and 1.10.3. When an import path is resolved to a
directory in `GOPATH` mode:
* When resolving an import of the form `$modpath/$vn/$dir` where:
* `$modpath` is a valid module path,
* `$vn` is a major version suffix,
* `$dir` is a possibly empty subdirectory,
* If all of the following are true:
* The package `$modpath/$vn/$dir` is not present in any relevant [`vendor`
directory](#glos-vendor-directory).
* A `go.mod` file is present in the same directory as the importing file
or in any parent directory up to the `$GOPATH/src` root,
* No `$GOPATH[i]/src/$modpath/$vn/$suffix` directory exists (for any root
`$GOPATH[i]`),
* The file `$GOPATH[d]/src/$modpath/go.mod` exists (for some root
`$GOPATH[d]`) and declares the module path as `$modpath/$vn`,
* Then the import of `$modpath/$vn/$dir` is resolved to the directory
`$GOPATH[d]/src/$modpath/$dir`.
This rules allow packages that have been migrated to modules to import other
packages that have been migrated to modules when built in `GOPATH` mode even
when a major version subdirectory was not used.
## Module-aware commands {#mod-commands}
Most `go` commands may run in *Module-aware mode* or *`GOPATH` mode*. In
module-aware mode, the `go` command uses `go.mod` files to find versioned
dependencies, and it typically loads packages out of the [module
cache](#glos-module-cache), downloading modules if they are missing. In `GOPATH`
mode, the `go` command ignores modules; it looks in [`vendor`
directories](#glos-vendor-directory) and in `GOPATH` to find dependencies.
As of Go 1.16, module-aware mode is enabled by default, regardless of whether a
`go.mod` file is present. In lower versions, module-aware mode was enabled when
a `go.mod` file was present in the current directory or any parent directory.
Module-aware mode may be controlled with the `GO111MODULE` environment variable,
which can be set to `on`, `off`, or `auto`.
* If `GO111MODULE=off`, the `go` command ignores `go.mod` files and runs in
`GOPATH` mode.
* If `GO111MODULE=on` or is unset, the `go` command runs in module-aware mode,
even when no `go.mod` file is present. Not all commands work without a
`go.mod` file: see [Module commands outside a module](#commands-outside).
* If `GO111MODULE=auto`, the `go` command runs in module-aware mode if a
`go.mod` file is present in the current directory or any parent directory.
In Go 1.15 and lower, this was the default behavior. `go mod` subcommands
and `go install` with a [version query](#version-queries) run in module-aware
mode even if no `go.mod` file is present.
In module-aware mode, `GOPATH` no longer defines the meaning of imports during a
build, but it still stores downloaded dependencies (in `GOPATH/pkg/mod`; see
[Module cache](#module-cache)) and installed commands (in `GOPATH/bin`, unless
`GOBIN` is set).
### Build commands {#build-commands}
All commands that load information about packages are module-aware. This
includes:
* `go build`
* `go fix`
* `go generate`
* `go install`
* `go list`
* `go run`
* `go test`
* `go vet`
When run in module-aware mode, these commands use `go.mod` files to interpret
import paths listed on the command line or written in Go source files. These
commands accept the following flags, common to all module commands.
* The `-mod` flag controls whether `go.mod` may be automatically updated and
whether the `vendor` directory is used.
* `-mod=mod` tells the `go` command to ignore the vendor directory and to
[automatically update](#go-mod-file-updates) `go.mod`, for example, when an
imported package is not provided by any known module.
* `-mod=readonly` tells the `go` command to ignore the `vendor` directory and
to report an error if `go.mod` needs to be updated.
* `-mod=vendor` tells the `go` command to use the `vendor` directory. In this
mode, the `go` command will not use the network or the module cache.
* By default, if the [`go` version](#go-mod-file-go) in `go.mod` is `1.14` or
higher and a `vendor` directory is present, the `go` command acts as if
`-mod=vendor` were used. Otherwise, the `go` command acts as if
`-mod=readonly` were used.
* `go get` rejects this flag as the purpose of the command is to modify
dependencies, which is only allowed by `-mod=mod`.
* The `-modcacherw` flag instructs the `go` command to create new directories
in the module cache with read-write permissions instead of making them
read-only. When this flag is used consistently (typically by setting
`GOFLAGS=-modcacherw` in the environment or by running
`go env -w GOFLAGS=-modcacherw`), the module cache may be deleted with
commands like `rm -r` without changing permissions first. The
[`go clean -modcache`](#go-clean-modcache) command may be used to delete the
module cache, whether or not `-modcacherw` was used.
* The `-modfile=file.mod` flag instructs the `go` command to read (and possibly
write) an alternate file instead of `go.mod` in the module root directory. The
file's name must end with `.mod`. A file named `go.mod` must still be present
in order to determine the module root directory, but it is not accessed. When
`-modfile` is specified, an alternate `go.sum` file is also used: its path is
derived from the `-modfile` flag by trimming the `.mod` extension and
appending `.sum`.
### Vendoring {#vendoring}
When using modules, the `go` command typically satisfies dependencies by
downloading modules from their sources into the module cache, then loading
packages from those downloaded copies. Vendoring may be used to allow
interoperation with older versions of Go, or to ensure that all files used for a
build are stored in a single file tree.
The [`go mod vendor`](#go-mod-vendor) command constructs a directory named
`vendor` in the [main module's](#glos-main-module) root directory containing
copies of all packages needed to build and test packages in the main module.
Packages that are only imported by tests of packages outside the main module are
not included. As with [`go mod tidy`](#go-mod-tidy) and other module commands,
[build constraints](#glos-build-constraint) except for `ignore` are not
considered when constructing the `vendor` directory.
`go mod vendor` also creates the file `vendor/modules.txt` that contains a list
of vendored packages and the module versions they were copied from. When
vendoring is enabled, this manifest is used as a source of module version
information, as reported by [`go list -m`](#go-list-m) and [`go version
-m`](#go-version-m). When the `go` command reads `vendor/modules.txt`, it checks
that the module versions are consistent with `go.mod`. If `go.mod` has changed
since `vendor/modules.txt` was generated, the `go` command will report an error.
`go mod vendor` should be run again to update the `vendor` directory.
If the `vendor` directory is present in the main module's root directory, it
will be used automatically if the [`go` version](#go-mod-file-go) in the main
module's [`go.mod` file](#glos-go-mod-file) is `1.14` or higher. To explicitly
enable vendoring, invoke the `go` command with the flag `-mod=vendor`. To
disable vendoring, use the flag `-mod=readonly` or `-mod=mod`.
When vendoring is enabled, [build commands](#build-commands) like `go build` and
`go test` load packages from the `vendor` directory instead of accessing the
network or the local module cache. The [`go list -m`](#go-list-m) command only
prints information about modules listed in `go.mod`. `go mod` commands such as
[`go mod download`](#go-mod-download) and [`go mod tidy`](#go-mod-tidy) do not
work differently when vendoring is enabled and will still download modules and
access the module cache. [`go get`](#go-get) also does not work differently when
vendoring is enabled.
Unlike [vendoring in `GOPATH` mode](/s/go15vendor), the `go`
command ignores vendor directories in locations other than the main module's
root directory. Additionally, since vendor directories in other modules are not
used, the `go` command does not include vendor directories when building [module
zip files](#zip-files) (but see known bugs
[#31562](/issue/31562) and
[#37397](/issue/37397)).
### `go get` {#go-get}
Usage:
```
go get [-d] [-t] [-u] [-tool] [build flags] [packages]
```
Examples:
```
# Upgrade a specific module.
$ go get golang.org/x/net
# Upgrade modules that provide packages imported by packages in the main module.
$ go get -u ./...
# Upgrade or downgrade to a specific version of a module.
$ go get golang.org/x/text@v0.3.2
# Update to the commit on the module's master branch.
$ go get golang.org/x/text@master
# Remove a dependency on a module and downgrade modules that require it
# to versions that don't require it.
$ go get golang.org/x/text@none
# Upgrade the minimum required Go version for the main module.
$ go get go
# Upgrade the suggested Go toolchain, leaving the minimum Go version alone.
$ go get toolchain
# Upgrade to the latest patch release of the suggested Go toolchain.
$ go get toolchain@patch
```
The `go get` command updates module dependencies in the [`go.mod`
file](#go-mod-file) for the [main module](#glos-main-module), then builds and
installs packages listed on the command line.
The first step is to determine which modules to update. `go get` accepts a list
of packages, package patterns, and module paths as arguments. If a package
argument is specified, `go get` updates the module that provides the package.
If a package pattern is specified (for example, `all` or a path with a `...`
wildcard), `go get` expands the pattern to a set of packages, then updates the
modules that provide the packages. If an argument names a module but not a
package (for example, the module `golang.org/x/net` has no package in its root
directory), `go get` will update the module but will not build a package. If no
arguments are specified, `go get` acts as if `.` were specified (the package in
the current directory); this may be used together with the `-u` flag to update
modules that provide imported packages.
Each argument may include a version query suffix indicating the
desired version, as in `go get golang.org/x/text@v0.3.0`. A version query
suffix consists of an `@` symbol followed by a [version query](#version-queries),
which may indicate a specific version (`v0.3.0`), a version prefix (`v0.3`),
a branch or tag name (`master`), a revision (`1234abcd`), or one of the special
queries `latest`, `upgrade`, `patch`, or `none`. If no version is given,
`go get` uses the `@upgrade` query.
Once `go get` has resolved its arguments to specific modules and versions, `go
get` will add, change, or remove [`require` directives](#go-mod-file-require) in
the main module's `go.mod` file to ensure the modules remain at the desired
versions in the future. Note that required versions in `go.mod` files are
*minimum versions* and may be increased automatically as new dependencies are
added. See [Minimal version selection (MVS)](#minimal-version-selection) for
details on how versions are selected and conflicts are resolved by module-aware
commands.
Other modules may be upgraded when a module named on the command line is added,
upgraded, or downgraded if the new version of the named module requires other
modules at higher versions. For example, suppose module `example.com/a` is
upgraded to version `v1.5.0`, and that version requires module `example.com/b`
at version `v1.2.0`. If module `example.com/b` is currently required at version
`v1.1.0`, `go get example.com/a@v1.5.0` will also upgrade `example.com/b` to
`v1.2.0`.

Other modules may be downgraded when a module named on the command line is
downgraded or removed. To continue the above example, suppose module
`example.com/b` is downgraded to `v1.1.0`. Module `example.com/a` would also be
downgraded to a version that requires `example.com/b` at version `v1.1.0` or
lower.

A module requirement may be removed using the version suffix `@none`. This is a
special kind of downgrade. Modules that depend on the removed module will be
downgraded or removed as needed. A module requirement may be removed even if one
or more of its packages are imported by packages in the main module. In this
case, the next build command may add a new module requirement.
If a module is needed at two different versions (specified explicitly in command
line arguments or to satisfy upgrades and downgrades), `go get` will report an
error.
After `go get` has selected a new set of versions, it checks whether any newly
selected module versions or any modules providing packages named on the command
line are [retracted](#glos-retracted-version) or
[deprecated](#glos-deprecated-module). `go get` prints a warning for each
retracted version or deprecated module it finds. [`go list -m -u
all`](#go-list-m) may be used to check for retractions and deprecations in all
dependencies.
After `go get` updates the `go.mod` file, it builds the packages named
on the command line. Executables will be installed in the directory named by
the `GOBIN` environment variable, which defaults to `$GOPATH/bin` or
`$HOME/go/bin` if the `GOPATH` environment variable is not set.
`go get` supports the following flags:
* The `-d` flag tells `go get` not to build or install packages. When `-d` is
used, `go get` will only manage dependencies in `go.mod`. Using `go get`
without `-d` to build and install packages is deprecated (as of Go 1.17).
In Go 1.18, `-d` will always be enabled.
* The `-u` flag tells `go get` to upgrade modules providing packages
imported directly or indirectly by packages named on the command line.
Each module selected by `-u` will be upgraded to its latest version unless
it is already required at a higher version (a pre-release).
* The `-u=patch` flag (not `-u patch`) also tells `go get` to upgrade
dependencies, but `go get` will upgrade each dependency to the latest patch
version (similar to the `@patch` version query).
* The `-t` flag tells `go get` to consider modules needed to build tests
of packages named on the command line. When `-t` and `-u` are used together,
`go get` will update test dependencies as well.
* The `-insecure` flag should no longer be used. It permits `go get` to resolve
custom import paths and fetch from repositories and module proxies using
insecure schemes such as HTTP. The `GOINSECURE` [environment
variable](#environment-variables) provides more fine-grained control and
should be used instead.
* The `-tool` flag instructs go to add a matching tool line to `go.mod` for each
listed package. If `-tool` is used with `@none`, the line will be removed.
Since Go 1.16, [`go install`](#go-install) is the recommended command for
building and installing programs. When used with a version suffix (like
`@latest` or `@v1.4.6`), `go install` builds packages in module-aware mode,
ignoring the `go.mod` file in the current directory or any parent directory,
if there is one.
`go get` is more focused on managing requirements in `go.mod`. The `-d` flag
is deprecated, and since Go 1.18, it is always enabled.
### `go install` {#go-install}
Usage:
```
go install [build flags] [packages]
```
Examples:
```
# Install the latest version of a program,
# ignoring go.mod in the current directory (if any).
$ go install golang.org/x/tools/gopls@latest
# Install a specific version of a program.
$ go install golang.org/x/tools/gopls@v0.6.4
# Install a program at the version selected by the module in the current directory.
$ go install golang.org/x/tools/gopls
# Install all programs in a directory.
$ go install ./cmd/...
```
The `go install` command builds and installs the packages named by the paths
on the command line. Executables (`main` packages) are installed to the
directory named by the `GOBIN` environment variable, which defaults to
`$GOPATH/bin` or `$HOME/go/bin` if the `GOPATH` environment variable is not set.
Executables in `$GOROOT` are installed in `$GOROOT/bin` or `$GOTOOLDIR` instead
of `$GOBIN`. Non-executable packages are built and cached but not installed.
Since Go 1.16, if the arguments have version suffixes (like `@latest` or
`@v1.0.0`), `go install` builds packages in module-aware mode, ignoring the
`go.mod` file in the current directory or any parent directory if there is
one. This is useful for installing executables without affecting the
dependencies of the main module.
To eliminate ambiguity about which module versions are used in the build, if any
of the arguments have version suffixes, the arguments must satisfy the following
constraints:
* Arguments must be package paths or package patterns (with "`...`" wildcards).
They must not be standard packages (like `fmt`), meta-patterns (`std`, `cmd`,
`all`, `work`, `tool`), or relative or absolute file paths. Note that `go install tool`
can be used without a version suffix: see below.
* All arguments must have the same version suffix. Different queries are not
allowed, even if they refer to the same version.
* All arguments must refer to packages in the same module at the same version.
* Package path arguments must refer to `main` packages. Pattern arguments
will only match `main` packages.
* No module is considered the [main module](#glos-main-module).
* If the module containing packages named on the command line has a `go.mod`
file, it must not contain directives (`replace` and `exclude`) that would
cause it to be interpreted differently if it were the main module.
* The module must not require a higher version of itself.
* Vendor directories are not used in any module. (Vendor directories are not
included in [module zip files](#zip-files), so `go install` does not
download them.)
See [Version queries](#version-queries) for supported version query syntax.
Go 1.15 and lower did not support using version queries with `go install`.
If the arguments don't have version suffixes, `go install` may run in
module-aware mode or `GOPATH` mode, depending on the `GO111MODULE` environment
variable and the presence of a `go.mod` file. See [Module-aware
commands](#mod-commands) for details. If module-aware mode is enabled, `go
install` runs in the context of the main module, which may be different from the
module containing the package being installed. In module-aware mode,
`go install tool` can be used from a module to install all the tools in the module.
### `go tool` {#go-tool}
Usage:
```
go tool [-n] command [args...]
```
Example:
```
$ go tool golang.org/x/tools/cmd/stringer
$ go tool stringer
```
In module mode, the `go tool` command can be used to build and run tools
declared in `go.mod` files using a [`tool` directive](#go-mod-file-tool).
The command can be specified using the full package path to a tool declared using
a tool directive. The default binary name of the tool, which is the last component of
the package path, excluding the major version suffix, can also be used if it is unique
among installed tools.
### `go list -m` {#go-list-m}
Usage:
```
go list -m [-u] [-retracted] [-versions] [list flags] [modules]
```
Example:
```
$ go list -m all
$ go list -m -versions example.com/m
$ go list -m -json example.com/m@latest
```
The `-m` flag causes `go list` to list modules instead of packages. In this
mode, the arguments to `go list` may be modules, module patterns (containing the
`...` wildcard), [version queries](#version-queries), or the special pattern
`all`, which matches all modules in the [build list](#glos-build-list). If no
arguments are specified, the [main module](#glos-main-module) is listed.
When listing modules, the `-f` flag still specifies a format template applied
to a Go struct, but now a `Module` struct:
```
type Module struct {
Path string // module path
Version string // module version
Versions []string // available module versions
Replace *Module // replaced by this module
Time *time.Time // time version was created
Update *Module // available update (with -u)
Main bool // is this the main module?
Indirect bool // module is only indirectly needed by main module
Dir string // directory holding local copy of files, if any
GoMod string // path to go.mod file describing module, if any
GoVersion string // go version used in module
Retracted []string // retraction information, if any (with -retracted or -u)
Deprecated string // deprecation message, if any (with -u)
Error *ModuleError // error loading module
}
type ModuleError struct {
Err string // the error itself
}
```
The default output is to print the module path and then information about the
version and replacement if any. For example, `go list -m all` might print:
```
example.com/main/module
golang.org/x/net v0.1.0
golang.org/x/text v0.3.0 => /tmp/text
rsc.io/pdf v0.1.1
```
The `Module` struct has a `String` method that formats this line of output, so
that the default format is equivalent to {{raw "`-f '{{.String}}'`"}}.
Note that when a module has been replaced, its `Replace` field describes the
replacement module, and its `Dir` field is set to the replacement
module's source code, if present. (That is, if `Replace` is non-nil, then `Dir`
is set to `Replace.Dir`, with no access to the replaced source code.)
The `-u` flag adds information about available upgrades. When the latest version
of a given module is newer than the current one, `list -u` sets the module's
`Update` field to information about the newer module. `list -u` also prints
whether the currently selected version is [retracted](#glos-retracted-version)
and whether the module is [deprecated](#go-mod-file-module-deprecation). The
module's `String` method indicates an available upgrade by formatting the newer
version in brackets after the current version. For example, `go list -m -u all`
might print:
```
example.com/main/module
golang.org/x/old v1.9.9 (deprecated)
golang.org/x/net v0.1.0 (retracted) [v0.2.0]
golang.org/x/text v0.3.0 [v0.4.0] => /tmp/text
rsc.io/pdf v0.1.1 [v0.1.2]
```
(For tools, `go list -m -u -json all` may be more convenient to parse.)
The `-versions` flag causes `list` to set the module's `Versions` field to a
list of all known versions of that module, ordered according to semantic
versioning, lowest to highest. The flag also changes the default output format
to display the module path followed by the space-separated version list.
Retracted versions are omitted from this list unless the `-retracted` flag
is also specified.
The `-retracted` flag instructs `list` to show retracted versions in the list
printed with the `-versions` flag and to consider retracted versions when
resolving [version queries](#version-queries). For example, `go list -m
-retracted example.com/m@latest` shows the highest release or pre-release
version of the module `example.com/m`, even if that version is retracted.
[`retract` directives](#go-mod-file-retract) and
[deprecations](#go-mod-file-module-deprecation) are loaded from the `go.mod`
file at this version. The `-retracted` flag was added in Go 1.16.
The template function `module` takes a single string argument that must be a
module path or query and returns the specified module as a `Module` struct. If
an error occurs, the result will be a `Module` struct with a non-nil `Error`
field.
### `go mod download` {#go-mod-download}
Usage:
```
go mod download [-x] [-json] [-reuse=old.json] [modules]
```
Example:
```
$ go mod download
$ go mod download golang.org/x/mod@v0.2.0
```
The `go mod download` command downloads the named modules into the [module
cache](#glos-module-cache). Arguments can be module paths or module
patterns selecting dependencies of the main module or [version
queries](#version-queries) of the form `path@version`. With no arguments,
`download` applies to all dependencies of the [main module](#glos-main-module).
The `go` command will automatically download modules as needed during ordinary
execution. The `go mod download` command is useful mainly for pre-filling the
module cache or for loading data to be served by a [module
proxy](#glos-module-proxy).
By default, `download` writes nothing to standard output. It prints progress
messages and errors to standard error.
The `-json` flag causes `download` to print a sequence of JSON objects to
standard output, describing each downloaded module (or failure), corresponding
to this Go struct:
```
type Module struct {
Path string // module path
Query string // version query corresponding to this version
Version string // module version
Error string // error loading module
Info string // absolute path to cached .info file
GoMod string // absolute path to cached .mod file
Zip string // absolute path to cached .zip file
Dir string // absolute path to cached source root directory
Sum string // checksum for path, version (as in go.sum)
GoModSum string // checksum for go.mod (as in go.sum)
Origin any // provenance of module
Reuse bool // reuse of old module info is safe
}
```
The `-x` flag causes `download` to print the commands `download` executes
to standard error.
The -reuse flag accepts the name of file containing the JSON output of a
previous 'go mod download -json' invocation. The go command may use this
file to determine that a module is unchanged since the previous invocation
and avoid redownloading it. Modules that are not redownloaded will be marked
in the new output by setting the Reuse field to true. Normally the module
cache provides this kind of reuse automatically; the -reuse flag can be
useful on systems that do not preserve the module cache.
### `go mod edit` {#go-mod-edit}
Usage:
```
go mod edit [editing flags] [-fmt|-print|-json] [go.mod]
```
Example:
```
# Add a replace directive.
$ go mod edit -replace example.com/a@v1.0.0=./a
# Remove a replace directive.
$ go mod edit -dropreplace example.com/a@v1.0.0
# Set the go version, add a requirement, and print the file
# instead of writing it to disk.
$ go mod edit -go=1.14 -require=example.com/m@v1.0.0 -print
# Format the go.mod file.
$ go mod edit -fmt
# Format and print a different .mod file.
$ go mod edit -print tools.mod
# Print a JSON representation of the go.mod file.
$ go mod edit -json
```
The `go mod edit` command provides a command-line interface for editing and
formatting `go.mod` files, for use primarily by tools and scripts. `go mod edit`
reads only one `go.mod` file; it does not look up information about other
modules. By default, `go mod edit` reads and writes the `go.mod` file of the
main module, but a different target file can be specified after the editing
flags.
The editing flags specify a sequence of editing operations.
* The `-module` flag changes the module's path (the `go.mod` file's module
line).
* The `-go=version` flag sets the expected Go language version.
* The `-require=path@version` and `-droprequire=path` flags add and drop a
requirement on the given module path and version. Note that `-require`
overrides any existing requirements on `path`. These flags are mainly for
tools that understand the module graph. Users should prefer `go get
path@version` or `go get path@none`, which make other `go.mod` adjustments as
needed to satisfy constraints imposed by other modules. See [`go
get`](#go-get).
* The `-exclude=path@version` and `-dropexclude=path@version` flags add and drop
an exclusion for the given module path and version. Note that
`-exclude=path@version` is a no-op if that exclusion already exists.
* The `-replace=old[@v]=new[@v]` flag adds a replacement of the given module
path and version pair. If the `@v` in `old@v` is omitted, a replacement
without a version on the left side is added, which applies to all versions of
the old module path. If the `@v` in `new@v` is omitted, the new path should be
a local module root directory, not a module path. Note that `-replace`
overrides any redundant replacements for `old[@v]`, so omitting `@v` will drop
replacements for specific versions.
* The `-dropreplace=old[@v]` flag drops a replacement of the given module path
and version pair. If the `@v` is provided, a replacement with the given
version is dropped. An existing replacement without a version on the left side
may still replace the module. If the `@v` is omitted, a replacement without a
version is dropped.
* The `-retract=version` and `-dropretract=version` flags add and drop a
retraction for the given version, which may be a single version (like
`v1.2.3`) or an interval (like `[v1.1.0,v1.2.0]`). Note that the `-retract`
flag cannot add a rationale comment for the `retract` directive. Rationale
comments are recommended and may be shown by `go list -m -u` and other
commands.
* The `-tool=path` and `-droptool=path` flags add and drop a `tool` directive
for the given paths. Note that this will not add necessary dependencies to
the build graph. Users should prefer `go get -tool path` to add a tool, or
`go get -tool path@none` to remove one.
The editing flags may be repeated. The changes are applied in the order given.
`go mod edit` has additional flags that control its output.
* The `-fmt` flag reformats the `go.mod` file without making other changes.
This reformatting is also implied by any other modifications that use or
rewrite the `go.mod` file. The only time this flag is needed is if no
other flags are specified, as in `go mod edit -fmt`.
* The `-print` flag prints the final `go.mod` in its text format instead of
writing it back to disk.
* The `-json` flag prints the final `go.mod` in JSON format instead of writing
it back to disk in text format. The JSON output corresponds to these Go types:
```
type Module struct {
Path string
Version string
}
type GoMod struct {
Module ModPath
Go string
Require []Require
Exclude []Module
Replace []Replace
Retract []Retract
}
type ModPath struct {
Path string
Deprecated string
}
type Require struct {
Path string
Version string
Indirect bool
}
type Replace struct {
Old Module
New Module
}
type Retract struct {
Low string
High string
Rationale string
}
type Tool struct {
Path string
}
```
Note that this only describes the `go.mod` file itself, not other modules
referred to indirectly. For the full set of modules available to a build,
use `go list -m -json all`. See [`go list -m`](#go-list-m).
For example, a tool can obtain the `go.mod` file as a data structure by
parsing the output of `go mod edit -json` and can then make changes by invoking
`go mod edit` with `-require`, `-exclude`, and so on.
Tools may also use the package
[`golang.org/x/mod/modfile`](https://pkg.go.dev/golang.org/x/mod/modfile?tab=doc)
to parse, edit, and format `go.mod` files.
### `go mod graph` {#go-mod-graph}
Usage:
```
go mod graph [-go=version]
```
The `go mod graph` command prints the [module requirement
graph](#glos-module-graph) (with replacements applied) in text form. For
example:
```
example.com/main example.com/a@v1.1.0
example.com/main example.com/b@v1.2.0
example.com/a@v1.1.0 example.com/b@v1.1.1
example.com/a@v1.1.0 example.com/c@v1.3.0
example.com/b@v1.1.0 example.com/c@v1.1.0
example.com/b@v1.2.0 example.com/c@v1.2.0
```
Each vertex in the module graph represents a specific version of a module.
Each edge in the graph represents a requirement on a minimum version of a
dependency.
`go mod graph` prints the edges of the graph, one per line. Each line has two
space-separated fields: a module version and one of its dependencies. Each
module version is identified as a string of the form `path@version`. The main
module has no `@version` suffix, since it has no version.
The `-go` flag causes `go mod graph` to report the module graph as
loaded by the given Go version, instead of the version indicated by
the [`go` directive](#go-mod-file-go) in the `go.mod` file.
See [Minimal version selection (MVS)](#minimal-version-selection) for more
information on how versions are chosen. See also [`go list -m`](#go-list-m) for
printing selected versions and [`go mod why`](#go-mod-why) for understanding
why a module is needed.
### `go mod init` {#go-mod-init}
Usage:
```
go mod init [module-path]
```
Example:
```
go mod init
go mod init example.com/m
```
The `go mod init` command initializes and writes a new `go.mod` file in the
current directory, in effect creating a new module rooted at the current
directory. The `go.mod` file must not already exist.
`init` accepts one optional argument, the [module path](#glos-module-path) for
the new module. See [Module paths](#module-path) for instructions on choosing
a module path. If the module path argument is omitted, `init` will attempt
to infer the module path using import comments in `.go` files and the
current directory (if in `GOPATH`).
### `go mod tidy` {#go-mod-tidy}
Usage:
```
go mod tidy [-e] [-v] [-x] [-diff] [-go=version] [-compat=version]
```
`go mod tidy` ensures that the `go.mod` file matches the source code in the
module. It adds any missing module requirements necessary to build the current
module's packages and dependencies, and it removes requirements on modules that
don't provide any relevant packages. It also adds any missing entries to
`go.sum` and removes unnecessary entries.
The `-e` flag (added in Go 1.16) causes `go mod tidy` to attempt to proceed
despite errors encountered while loading packages.
The `-v` flag causes `go mod tidy` to print information about removed modules
to standard error.
The `-x` flag causes `go mod tidy` to print the commands `tidy` executes.
The `-diff` flag causes `go mod tidy` not to modify go.mod or go.sum but
instead print the necessary changes as a unified diff. It exits
with a non-zero code if the diff is not empty.
`go mod tidy` works by loading all of the packages in the [main
module](#glos-main-module), all of its tools, and all of the packages they import,
recursively. This includes packages imported by tests (including tests in other
modules). `go mod tidy` acts as if all build tags are enabled, so it will
consider platform-specific source files and files that require custom build
tags, even if those source files wouldn't normally be built. There is one
exception: the `ignore` build tag is not enabled, so a file with the build
constraint `// +build ignore` will not be considered. Note that `go mod tidy`
will not consider packages in the main module in directories named `testdata` or
with names that start with `.` or `_` unless those packages are explicitly
imported by other packages.
Once `go mod tidy` has loaded this set of packages, it ensures that each module
that provides one or more packages has a `require` directive in the main
module's `go.mod` file or — if the main module is at `go 1.16` or below — is
required by another required module. `go mod tidy` will add a requirement on the
latest version of each missing module (see [Version queries](#version-queries)
for the definition of the `latest` version). `go mod tidy` will remove `require`
directives for modules that don't provide any packages in the set described
above.
`go mod tidy` may also add or remove `// indirect` comments on `require`
directives. An `// indirect` comment denotes a module that does not provide a
package imported by a package in the main module. (See the [`require`
directive](#go-mod-file-require) for more detail on when `// indirect`
dependencies and comments are added.)
If the `-go` flag is set, `go mod tidy` will update the [`go`
directive](#go-mod-file-go) to the indicated version, enabling or disabling
[module graph pruning](#graph-pruning) and [lazy module loading](#lazy-loading)
(and adding or removing indirect requirements as needed) according to that
version.
By default, `go mod tidy` will check that the [selected
versions](#glos-selected-version) of modules do not change when the module graph
is loaded by the Go version immediately preceding the version indicated in the
`go` directive. The versioned checked for compatibility can also be specified
explicitly via the `-compat` flag.
### `go mod vendor` {#go-mod-vendor}
Usage:
```
go mod vendor [-e] [-v] [-o]
```
The `go mod vendor` command constructs a directory named `vendor` in the [main
module's](#glos-main-module) root directory that contains copies of all packages
needed to support builds and tests of packages in the main module. Packages
that are only imported by tests of packages outside the main module are not
included. As with [`go mod tidy`](#go-mod-tidy) and other module commands,
[build constraints](#glos-build-constraint) except for `ignore` are not
considered when constructing the `vendor` directory.
When vendoring is enabled, the `go` command will load packages from the `vendor`
directory instead of downloading modules from their sources into the module
cache and using packages those downloaded copies. See [Vendoring](#vendoring)
for more information.
`go mod vendor` also creates the file `vendor/modules.txt` that contains a list
of vendored packages and the module versions they were copied from. When
vendoring is enabled, this manifest is used as a source of module version
information, as reported by [`go list -m`](#go-list-m) and [`go version
-m`](#go-version-m). When the `go` command reads `vendor/modules.txt`, it checks
that the module versions are consistent with `go.mod`. If `go.mod` changed since
`vendor/modules.txt` was generated, `go mod vendor` should be run again.
Note that `go mod vendor` removes the `vendor` directory if it exists before
re-constructing it. Local changes should not be made to vendored packages.
The `go` command does not check that packages in the `vendor` directory have
not been modified, but one can verify the integrity of the `vendor` directory
by running `go mod vendor` and checking that no changes were made.
The `-e` flag (added in Go 1.16) causes `go mod vendor` to attempt to proceed
despite errors encountered while loading packages.
The `-v` flag causes `go mod vendor` to print the names of vendored modules
and packages to standard error.
The `-o` flag (added in Go 1.18) causes `go mod vendor` to output the vendor
tree at the specified directory instead of `vendor`. The argument can be either
an absolute path or a path relative to the module root.
### `go mod verify` {#go-mod-verify}
Usage:
```
go mod verify
```
`go mod verify` checks that dependencies of the [main module](#glos-main-module)
stored in the [module cache](#glos-module-cache) have not been modified since
they were downloaded. To perform this check, `go mod verify` hashes each
downloaded module [`.zip` file](#zip-files) and extracted directory, then
compares those hashes with a hash recorded when the module was first
downloaded. `go mod verify` checks each module in the [build
list](#glos-build-list) (which may be printed with [`go list -m
all`](#go-list-m)).
If all the modules are unmodified, `go mod verify` prints "all modules
verified". Otherwise, it reports which modules have been changed and exits with
a non-zero status.
Note that all module-aware commands verify that hashes in the main module's
`go.sum` file match hashes recorded for modules downloaded into the module
cache. If a hash is missing from `go.sum` (for example, because the module is
being used for the first time), the `go` command verifies its hash using the
[checksum database](#checksum-database) (unless the module path is matched by
`GOPRIVATE` or `GONOSUMDB`). See [Authenticating modules](#authenticating) for
details.
In contrast, `go mod verify` checks that module `.zip` files and their extracted
directories have hashes that match hashes recorded in the module cache when they
were first downloaded. This is useful for detecting changes to files in the
module cache *after* a module has been downloaded and verified. `go mod verify`
does not download content for modules not in the cache, and it does not use
`go.sum` files to verify module content. However, `go mod verify` may download
`go.mod` files in order to perform [minimal version
selection](#minimal-version-selection). It will use `go.sum` to verify those
files, and it may add `go.sum` entries for missing hashes.
### `go mod why` {#go-mod-why}
Usage:
```
go mod why [-m] [-vendor] packages...
```
`go mod why` shows a shortest path in the import graph from the main module to
each of the listed packages.
The output is a sequence of stanzas, one for each package or module named on the
command line, separated by blank lines. Each stanza begins with a comment line
starting with `#` giving the target package or module. Subsequent lines give a
path through the import graph, one package per line. If the package or module
is not referenced from the main module, the stanza will display a single
parenthesized note indicating that fact.
For example:
```
$ go mod why golang.org/x/text/language golang.org/x/text/encoding
# golang.org/x/text/language
rsc.io/quote
rsc.io/sampler
golang.org/x/text/language
# golang.org/x/text/encoding
(main module does not need package golang.org/x/text/encoding)
```
The `-m` flag causes `go mod why` to treat its arguments as a list of modules.
`go mod why` will print a path to any package in each of the modules. Note that
even when `-m` is used, `go mod why` queries the package graph, not the
module graph printed by [`go mod graph`](#go-mod-graph).
The `-vendor` flag causes `go mod why` to ignore imports in tests of packages
outside the main module (as [`go mod vendor`](#go-mod-vendor) does). By default,
`go mod why` considers the graph of packages matched by the `all` pattern. This
flag has no effect after Go 1.16 in modules that declare `go 1.16` or higher
(using the [`go` directive](#go-mod-file-go) in `go.mod`), since the meaning of
`all` changed to match the set of packages matched by `go mod vendor`.
### `go version -m` {#go-version-m}
Usage:
```
go version [-m] [-v] [file ...]
```
Example:
```
# Print Go version used to build go.
$ go version
# Print Go version used to build a specific executable.
$ go version ~/go/bin/gopls
# Print Go version and module versions used to build a specific executable.
$ go version -m ~/go/bin/gopls
# Print Go version and module versions used to build executables in a directory.
$ go version -m ~/go/bin/
```
`go version` reports the Go version used to build each executable file named
on the command line.
If no files are named on the command line, `go version` prints its own version
information.
If a directory is named, `go version` walks that directory, recursively, looking
for recognized Go binaries and reporting their versions. By default, `go
version` does not report unrecognized files found during a directory scan. The
`-v` flag causes it to report unrecognized files.
The `-m` flag causes `go version` to print each executable's embedded module
version information, when available. For each executable, `go version -m` prints
a table with tab-separated columns like the one below.
```
$ go version -m ~/go/bin/goimports
/home/jrgopher/go/bin/goimports: go1.14.3
path golang.org/x/tools/cmd/goimports
mod golang.org/x/tools v0.0.0-20200518203908-8018eb2c26ba h1:0Lcy64USfQQL6GAJma8BdHCgeofcchQj+Z7j0SXYAzU=
dep golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ=
dep golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
```
The format of the table may change in the future. The same information may be
obtained from
[`runtime/debug.ReadBuildInfo`](https://pkg.go.dev/runtime/debug?tab=doc#ReadBuildInfo).
The meaning of each row in the table is determined by the word in the first
column.
* **`path`**: the path of the `main` package used to build the executable.
* **`mod`**: the module containing the `main` package. The columns are the
module path, version, and sum, respectively. The [main
module](#glos-main-module) has the version `(devel)` and no sum.
* **`dep`**: a module that provided one or more packages linked into the
executable. Same format as `mod`.
* **`=>`**: a [replacement](#go-mod-file-replace) for the module on the previous
line. If the replacement is a local directory, only the directory path is
listed (no version or sum). If the replacement is a module version, the path,
version, and sum are listed, as with `mod` and `dep`. A replaced module has
no sum.
### `go clean -modcache` {#go-clean-modcache}
Usage:
```
go clean [-modcache]
```
The `-modcache` flag causes [`go
clean`](/cmd/go/#hdr-Remove_object_files_and_cached_files) to remove the entire
[module cache](#glos-module-cache), including unpacked source code of versioned
dependencies.
This is usually the best way to remove the module cache. By default, most files
and directories in the module cache are read-only to prevent tests and editors
from unintentionally changing files after they've been
[authenticated](#authenticating). Unfortunately, this causes commands like
`rm -r` to fail, since files can't be removed without first making their parent
directories writable.
The `-modcacherw` flag (accepted by [`go
build`](/cmd/go/#hdr-Compile_packages_and_dependencies) and
other module-aware commands) causes new directories in the module cache to
be writable. To pass `-modcacherw` to all module-aware commands, add it to the
`GOFLAGS` variable. `GOFLAGS` may be set in the environment or with [`go env
-w`](/cmd/go/#hdr-Print_Go_environment_information). For
example, the command below sets it permanently:
```
go env -w GOFLAGS=-modcacherw
```
`-modcacherw` should be used with caution; developers should be careful not
to make changes to files in the module cache. [`go mod verify`](#go-mod-verify)
may be used to check that files in the cache match hashes in the main module's
`go.sum` file.
### Version queries {#version-queries}
Several commands allow you to specify a version of a module using a *version
query*, which appears after an `@` character following a module or package path
on the command line.
Examples:
```
go get example.com/m@latest
go mod download example.com/m@master
go list -m -json example.com/m@e3702bed2
```
A version query may be one of the following:
* A fully-specified semantic version, such as `v1.2.3`, which selects a
specific version. See [Versions](#versions) for syntax.
* A semantic version prefix, such as `v1` or `v1.2`, which selects the highest
available version with that prefix.
* A semantic version comparison, such as {{raw "`go buildgo docgo fixgo fmtgo generatego installgo listgo rungo testgo vet
.go files on the command line can be loaded, imported, and
built. Packages from other modules cannot be built, since there is no
place to record module requirements and ensure deterministic builds.
go getgo get is run without a
go.mod file, so replace and
exclude directives are not applied.
go list -m-versions flag is used.
go mod downloadgo mod editgo mod graphgo mod tidygo mod vendorgo mod verifygo mod why
go.mod file and will report
an error if one is not present.
| Path | Description |
|---|---|
$base/$module/@v/list |
Returns a list of known versions of the given module in plain text, one per line. This list should not include pseudo-versions. |
$base/$module/@v/$version.info |
Returns JSON-formatted metadata about a specific version of a module. The response must be a JSON object that corresponds to the Go data structure below:
type Info struct {
Version string // version string
Time time.Time // commit time
}
The
The More fields may be added in the future, so other names are reserved. |
$base/$module/@v/$version.mod |
Returns the go.mod file for a specific version of a
module. If the module does not have a go.mod file at the
requested version, a file containing only a module
statement with the requested module path must be returned. Otherwise,
the original, unmodified go.mod file must be returned.
|
$base/$module/@v/$version.zip |
Returns a zip file containing the contents of a specific version of a module. See Module zip files for details on how this zip file must be formatted. |
$base/$module/@latest |
Returns JSON-formatted metadata about the latest known version of a
module in the same format as
$base/$module/@v/$version.info. The latest version should
be the version of the module that the go command should use
if $base/$module/@v/list is empty or no listed version is
suitable. This endpoint is optional, and module proxies are not required
to implement it.
|
| Name | Command | GOVCS default | Secure schemes |
|---|---|---|---|
| Bazaar | bzr |
Private only | https, bzr+ssh |
| Fossil | fossil |
Private only | https |
| Git | git |
Public and private | https, git+ssh, ssh |
| Mercurial | hg |
Public and private | https, ssh |
| Subversion | svn |
Private only | https, svn+ssh |
| Path | Description |
|---|---|
$module@$version/ |
Directory containing extracted contents of a module .zip
file. This serves as a module root directory for a downloaded module. It
won't contain a go.mod file if the original module
didn't have one.
|
cache/download/ |
Directory containing files downloaded from module proxies and files
derived from version control systems. The layout of
this directory follows the
GOPROXY protocol, so
this directory may be used as a proxy when served by an HTTP file
server or when referenced with a file:// URL.
|
cache/download/$module/@v/list |
List of known versions (see
GOPROXY protocol). This
may change over time, so the go command usually fetches a
new copy instead of re-using this file.
|
cache/download/$module/@v/$version.info |
JSON metadata about the version. (see
GOPROXY protocol). This
may change over time, so the go command usually fetches a
new copy instead of re-using this file.
|
cache/download/$module/@v/$version.mod |
The go.mod file for this version (see
GOPROXY protocol). If
the original module did not have a go.mod file, this is
a synthesized file with no requirements.
|
cache/download/$module/@v/$version.zip |
The zipped contents of the module (see
GOPROXY protocol and
Module zip files).
|
cache/download/$module/@v/$version.ziphash |
A cryptographic hash of the files in the .zip file.
Note that the .zip file itself is not hashed, so file
order, compression, alignment, and metadata don't affect the hash.
When using a module, the go command verifies this hash
matches the corresponding line in
go.sum. The
go mod verify command checks
that the hashes of module .zip files and extracted
directories match these files.
|
cache/download/sumdb/ |
Directory containing files downloaded from a
checksum database (typically
sum.golang.org).
|
cache/vcs/ |
Contains cloned version control repositories for modules fetched directly from their sources. Directory names are hex-encoded hashes derived from the repository type and URL. Repositories are optimized for size on disk. For example, cloned Git repositories are bare and shallow when possible. |
| Path | Description |
|---|---|
$base/latest |
Returns a signed, encoded tree description for the latest log. This
signed description is in the form of a
note,
which is text that has been signed by one or more server keys and can
be verified using the server's public key. The tree description
provides the size of the tree and the hash of the tree head at that
size. This encoding is described in
golang.org/x/mod/sumdb/tlog#FormatTree.
|
$base/lookup/$module@$version |
Returns the log record number for the entry about $module
at $version, followed by the data for the record (that is,
the go.sum lines for $module at
$version) and a signed, encoded tree description that
contains the record.
|
$base/tile/$H/$L/$K[.p/$W] |
Returns a log tile,
which is a set of hashes that make up a section of the log. Each tile
is defined in a two-dimensional coordinate at tile level
$L, $Kth from the left, with a tile height of
$H. The optional .p/$W suffix indicates a
partial log tile with only $W hashes. Clients must fall
back to fetching the full tile if a partial tile is not found.
|
$base/tile/$H/data/$K[.p/$W] |
Returns the record data for the leaf hashes in
/tile/$H/0/$K[.p/$W] (with a literal data path
element).
|
| Variable | Description |
|---|---|
GO111MODULE |
Controls whether the
See Module-aware commands for more information. |
GOMODCACHE |
The directory where the
If |
GOINSECURE |
Comma-separated list of glob patterns (in the syntax of Go's
Unlike the |
GONOPROXY |
Comma-separated list of glob patterns (in the syntax of Go's
If |
GONOSUMDB |
Comma-separated list of glob patterns (in the syntax of Go's
If |
GOPATH |
In
In module-aware mode, the module
cache is stored in the
If |
GOPRIVATE |
Comma-separated list of glob patterns (in the syntax of Go's
path.Match) of module path
prefixes that should be considered private. GOPRIVATE
is a default value for GONOPROXY and
GONOSUMDB. See
Privacy. GOPRIVATE
also determines whether a module is considered private for
GOVCS.
|
GOPROXY |
List of module proxy URLs, separated by commas (
The
GOPROXY=file://$(go env GOMODCACHE)/cache/download Two keywords may be used in place of proxy URLs:
See Module proxies and Resolving a package to a module for more information on how proxies are used. |
GOSUMDB |
Identifies the name of the checksum database to use and optionally its public key and URL. For example: GOSUMDB="sum.golang.org" GOSUMDB="sum.golang.org+<publickey>" GOSUMDB="sum.golang.org+<publickey> https://sum.golang.org"
The
If See Authenticating modules and Privacy for more information. |
GOVCS |
Controls the set of version control tools the
If public:git|hg,private:all
See Controlling version control tools with
|
GOWORK |
The |