Movatterモバイル変換


[0]ホーム

URL:


go

commandstandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:38Imported by:4

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Go is a tool for managing Go source code.

Usage:

go <command> [arguments]

The commands are:

bug         start a bug reportbuild       compile packages and dependenciesclean       remove object files and cached filesdoc         show documentation for package or symbolenv         print Go environment informationfix         update packages to use new APIsfmt         gofmt (reformat) package sourcesgenerate    generate Go files by processing sourceget         add dependencies to current module and install theminstall     compile and install packages and dependencieslist        list packages or modulesmod         module maintenancework        workspace maintenancerun         compile and run Go programtelemetry   manage telemetry data and settingstest        test packagestool        run specified go toolversion     print Go versionvet         report likely mistakes in packages

Use "go help <command>" for more information about a command.

Additional help topics:

buildconstraint build constraintsbuildjson       build -json encodingbuildmode       build modesc               calling between Go and Ccache           build and test cachingenvironment     environment variablesfiletype        file typesgoauth          GOAUTH environment variablego.mod          the go.mod filegopath          GOPATH environment variablegoproxy         module proxy protocolimportpath      import path syntaxmodules         modules, module versions, and moremodule-auth     module authentication using go.sumpackages        package lists and patternsprivate         configuration for downloading non-public codetestflag        testing flagstestfunc        testing functionsvcs             controlling version control with GOVCS

Use "go help <topic>" for more information about that topic.

Start a bug report

Usage:

go bug

Bug opens the default browser and starts a new bug report.The report includes useful system information.

Compile packages and dependencies

Usage:

go build [-o output] [build flags] [packages]

Build compiles the packages named by the import paths,along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files from a single directory,build treats them as a list of source files specifying a single package.

When compiling packages, build ignores files that end in '_test.go'.

When compiling a single main package, build writes the resultingexecutable to an output file named after the last non-major-versioncomponent of the package import path. The '.exe' suffix is addedwhen writing a Windows executable.So 'go build example/sam' writes 'sam' or 'sam.exe'.'go build example.com/foo/v2' writes 'foo' or 'foo.exe', not 'v2.exe'.

When compiling a package from a list of .go files, the executableis named after the first source file.'go build ed.go rx.go' writes 'ed' or 'ed.exe'.

When compiling multiple packages or a single non-main package,build compiles the packages but discards the resulting object,serving only as a check that the packages can be built.

The -o flag forces build to write the resulting executable or objectto the named output file or directory, instead of the default behavior describedin the last two paragraphs. If the named output is an existing directory orends with a slash or backslash, then any resulting executableswill be written to that directory.

The build flags are shared by the build, clean, get, install, list, run,and test commands:

-C dirChange to dir before running the command.Any files named on the command line are interpreted afterchanging directories.If used, this flag must be the first one in the command line.-aforce rebuilding of packages that are already up-to-date.-nprint the commands but do not run them.-p nthe number of programs, such as build commands ortest binaries, that can be run in parallel.The default is GOMAXPROCS, normally the number of CPUs available.-raceenable data race detection.Supported only on linux/amd64, freebsd/amd64, darwin/amd64, darwin/arm64, windows/amd64,linux/ppc64le and linux/arm64 (only for 48-bit VMA).-msanenable interoperation with memory sanitizer.Supported only on linux/amd64, linux/arm64, linux/loong64, freebsd/amd64and only with Clang/LLVM as the host C compiler.PIE build mode will be used on all platforms except linux/amd64.-asanenable interoperation with address sanitizer.Supported only on linux/arm64, linux/amd64, linux/loong64.Supported on linux/amd64 or linux/arm64 and only with GCC 7 and higheror Clang/LLVM 9 and higher.And supported on linux/loong64 only with Clang/LLVM 16 and higher.-coverenable code coverage instrumentation.-covermode set,count,atomicset the mode for coverage analysis.The default is "set" unless -race is enabled,in which case it is "atomic".The values:set: bool: does this statement run?count: int: how many times does this statement run?atomic: int: count, but correct in multithreaded tests;significantly more expensive.Sets -cover.-coverpkg pattern1,pattern2,pattern3For a build that targets package 'main' (e.g. building a Goexecutable), apply coverage analysis to each package whoseimport path matches the patterns. The default is to applycoverage analysis to packages in the main Go module. See'go help packages' for a description of package patterns.Sets -cover.-vprint the names of packages as they are compiled.-workprint the name of the temporary work directory anddo not delete it when exiting.-xprint the commands.-asmflags '[pattern=]arg list'arguments to pass on each go tool asm invocation.-buildmode modebuild mode to use. See 'go help buildmode' for more.-buildvcsWhether to stamp binaries with version control information("true", "false", or "auto"). By default ("auto"), version controlinformation is stamped into a binary if the main package, the main modulecontaining it, and the current directory are all in the same repository.Use -buildvcs=false to always omit version control information, or-buildvcs=true to error out if version control information is available butcannot be included due to a missing tool or ambiguous directory structure.-compiler namename of compiler to use, as in runtime.Compiler (gccgo or gc).-gccgoflags '[pattern=]arg list'arguments to pass on each gccgo compiler/linker invocation.-gcflags '[pattern=]arg list'arguments to pass on each go tool compile invocation.-installsuffix suffixa suffix to use in the name of the package installation directory,in order to keep output separate from default builds.If using the -race flag, the install suffix is automatically set to raceor, if set explicitly, has _race appended to it. Likewise for the -msanand -asan flags. Using a -buildmode option that requires non-default compileflags has a similar effect.-jsonEmit build output in JSON suitable for automated processing.See 'go help buildjson' for the encoding details.-ldflags '[pattern=]arg list'arguments to pass on each go tool link invocation.-linksharedbuild code that will be linked against shared libraries previouslycreated with -buildmode=shared.-mod modemodule download mode to use: readonly, vendor, or mod.By default, if a vendor directory is present and the go version in go.modis 1.14 or higher, the go command acts as if -mod=vendor were set.Otherwise, the go command acts as if -mod=readonly were set.See https://golang.org/ref/mod#build-commands for details.-modcacherwleave newly-created directories in the module cache read-writeinstead of making them read-only.-modfile filein module aware mode, read (and possibly write) an alternate go.modfile instead of the one in the module root directory. A file named"go.mod" must still be present in order to determine the module rootdirectory, but it is not accessed. When -modfile is specified, analternate go.sum file is also used: its path is derived from the-modfile flag by trimming the ".mod" extension and appending ".sum".-overlay fileread a JSON config file that provides an overlay for build operations.The file is a JSON object with a single field, named 'Replace', thatmaps each disk file path (a string) to its backing file path, so thata build will run as if the disk file path exists with the contentsgiven by the backing file paths, or as if the disk file path does notexist if its backing file path is empty. Support for the -overlay flaghas some limitations: importantly, cgo files included from outside theinclude path must be in the same directory as the Go package they areincluded from, overlays will not appear when binaries and tests arerun through go run and go test respectively, and files beneathGOMODCACHE may not be replaced.-pgo filespecify the file path of a profile for profile-guided optimization (PGO).When the special name "auto" is specified, for each main package in thebuild, the go command selects a file named "default.pgo" in the package'sdirectory if that file exists, and applies it to the (transitive)dependencies of the main package (other packages are not affected).Special name "off" turns off PGO. The default is "auto".-pkgdir dirinstall and load all packages from dir instead of the usual locations.For example, when building with a non-standard configuration,use -pkgdir to keep generated packages in a separate location.-tags tag,lista comma-separated list of additional build tags to consider satisfiedduring the build. For more information about build tags, see'go help buildconstraint'. (Earlier versions of Go used aspace-separated list, and that form is deprecated but still recognized.)-trimpathremove all file system paths from the resulting executable.Instead of absolute file system paths, the recorded file nameswill begin either a module path@version (when using modules),or a plain import path (when using the standard library, or GOPATH).-toolexec 'cmd args'a program to use to invoke toolchain programs like vet and asm.For example, instead of running asm, the go command will run'cmd args /path/to/asm <arguments for asm>'.The TOOLEXEC_IMPORTPATH environment variable will be set,matching 'go list -f {{.ImportPath}}' for the package being built.

The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept aspace-separated list of arguments to pass to an underlying toolduring the build. To embed spaces in an element in the list, surroundit with either single or double quotes. The argument list may bepreceded by a package pattern and an equal sign, which restrictsthe use of that argument list to the building of packages matchingthat pattern (see 'go help packages' for a description of packagepatterns). Without a pattern, the argument list applies only to thepackages named on the command line. The flags may be repeatedwith different patterns in order to specify different arguments fordifferent sets of packages. If a package matches patterns given inmultiple flags, the latest match on the command line wins.For example, 'go build -gcflags=-S fmt' prints the disassemblyonly for package fmt, while 'go build -gcflags=all=-S fmt'prints the disassembly for fmt and all its dependencies.

For more about specifying packages, see 'go help packages'.For more about where packages and binaries are installed,run 'go help gopath'.For more about calling between Go and C/C++, run 'go help c'.

Note: Build adheres to certain conventions such as those describedby 'go help gopath'. Not all projects can follow these conventions,however. Installations that have their own conventions or that usea separate software build system may choose to use lower-levelinvocations such as 'go tool compile' and 'go tool link' to avoidsome of the overheads and design decisions of the build tool.

See also: go install, go get, go clean.

Remove object files and cached files

Usage:

go clean [-i] [-r] [-cache] [-testcache] [-modcache] [-fuzzcache] [build flags] [packages]

Clean removes object files from package source directories.The go command builds most objects in a temporary directory,so go clean is mainly concerned with object files left by othertools or by manual invocations of go build.

If a package argument is given or the -i or -r flag is set,clean removes the following files from each of thesource directories corresponding to the import paths:

_obj/            old object directory, left from Makefiles_test/           old test directory, left from Makefiles_testmain.go     old gotest file, left from Makefilestest.out         old test log, left from Makefilesbuild.out        old test log, left from Makefiles*.[568ao]        object files, left from MakefilesDIR(.exe)        from go buildDIR.test(.exe)   from go test -cMAINFILE(.exe)   from go build MAINFILE.go*.so             from SWIG

In the list, DIR represents the final path element of thedirectory, and MAINFILE is the base name of any Go sourcefile in the directory that is not included when buildingthe package.

The -i flag causes clean to remove the corresponding installedarchive or binary (what 'go install' would create).

The -n flag causes clean to print the remove commands it would execute,but not run them.

The -r flag causes clean to be applied recursively to all thedependencies of the packages named by the import paths.

The -x flag causes clean to print remove commands as it executes them.

The -cache flag causes clean to remove the entire go build cache.

The -testcache flag causes clean to expire all test results in thego build cache.

The -modcache flag causes clean to remove the entire moduledownload cache, including unpacked source code of versioneddependencies.

The -fuzzcache flag causes clean to remove files stored in the Go buildcache for fuzz testing. The fuzzing engine caches files that expandcode coverage, so removing them may make fuzzing less effective untilnew inputs are found that provide the same coverage. These files aredistinct from those stored in testdata directory; clean does not removethose files.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

Show documentation for package or symbol

Usage:

go doc [doc flags] [package|[package.]symbol[.methodOrField]]

Doc prints the documentation comments associated with the item identified by itsarguments (a package, const, func, type, var, method, or struct field)followed by a one-line summary of each of the first-level items "under"that item (package-level declarations for a package, methods for a type,etc.).

Doc accepts zero, one, or two arguments.

Given no arguments, that is, when run as

go doc

it prints the package documentation for the package in the current directory.If the package is a command (package main), the exported symbols of the packageare elided from the presentation unless the -cmd flag is provided.

When run with one argument, the argument is treated as a Go-syntax-likerepresentation of the item to be documented. What the argument selects dependson what is installed in GOROOT and GOPATH, as well as the form of the argument,which is schematically one of these:

go doc <pkg>go doc <sym>[.<methodOrField>]go doc [<pkg>.]<sym>[.<methodOrField>]go doc [<pkg>.][<sym>.]<methodOrField>

The first item in this list matched by the argument is the one whose documentationis printed. (See the examples below.) However, if the argument starts with a capitalletter it is assumed to identify a symbol or method in the current directory.

For packages, the order of scanning is determined lexically in breadth-first order.That is, the package presented is the one that matches the search and is nearestthe root and lexically first at its level of the hierarchy. The GOROOT tree isalways scanned in its entirety before GOPATH.

If there is no package specified or matched, the package in the currentdirectory is selected, so "go doc Foo" shows the documentation for symbol Foo inthe current package.

The package path must be either a qualified path or a proper suffix of apath. The go tool's usual package mechanism does not apply: package pathelements like . and ... are not implemented by go doc.

When run with two arguments, the first is a package path (full path or suffix),and the second is a symbol, or symbol with method or struct field:

go doc <pkg> <sym>[.<methodOrField>]

In all forms, when matching symbols, lower-case letters in the argument matcheither case but upper-case letters match exactly. This means that there may bemultiple matches of a lower-case argument in a package if different symbols havedifferent cases. If this occurs, documentation for all matches is printed.

Examples:

go docShow documentation for current package.go doc -httpServe HTML documentation over HTTP for the current package.go doc FooShow documentation for Foo in the current package.(Foo starts with a capital letter so it cannot matcha package path.)go doc encoding/jsonShow documentation for the encoding/json package.go doc jsonShorthand for encoding/json.go doc json.Number (or go doc json.number)Show documentation and method summary for json.Number.go doc json.Number.Int64 (or go doc json.number.int64)Show documentation for json.Number's Int64 method.go doc cmd/docShow package docs for the doc command.go doc -cmd cmd/docShow package docs and exported symbols within the doc command.go doc template.newShow documentation for html/template's New function.(html/template is lexically before text/template)go doc text/template.new # One argumentShow documentation for text/template's New function.go doc text/template new # Two argumentsShow documentation for text/template's New function.At least in the current tree, these invocations all print thedocumentation for json.Decoder's Decode method:go doc json.Decoder.Decodego doc json.decoder.decodego doc json.decodecd go/src/encoding/json; go doc decode

Flags:

-allShow all the documentation for the package.-cRespect case when matching symbols.-cmdTreat a command (package main) like a regular package.Otherwise package main's exported symbols are hiddenwhen showing the package's top-level documentation.  -httpServe HTML docs over HTTP.-shortOne-line representation for each symbol.-srcShow the full source code for the symbol. This willdisplay the full Go source of its declaration anddefinition, such as a function definition (includingthe body), type declaration or enclosing constblock. The output may therefore include unexporteddetails.-uShow documentation for unexported as well as exportedsymbols, methods, and fields.

Print Go environment information

Usage:

go env [-json] [-changed] [-u] [-w] [var ...]

Env prints Go environment information.

By default env prints information as a shell script(on Windows, a batch file). If one or more variablenames is given as arguments, env prints the value ofeach named variable on its own line.

The -json flag prints the environment in JSON formatinstead of as a shell script.

The -u flag requires one or more arguments and unsetsthe default setting for the named environment variables,if one has been set with 'go env -w'.

The -w flag requires one or more arguments of theform NAME=VALUE and changes the default settingsof the named environment variables to the given values.

The -changed flag prints only those settings whose effectivevalue differs from the default value that would be obtained inan empty environment with no prior uses of the -w flag.

For more about environment variables, see 'go help environment'.

Update packages to use new APIs

Usage:

go fix [-fix list] [packages]

Fix runs the Go fix command on the packages named by the import paths.

The -fix flag sets a comma-separated list of fixes to run.The default is all known fixes.(Its value is passed to 'go tool fix -r'.)

For more about fix, see 'go doc cmd/fix'.For more about specifying packages, see 'go help packages'.

To run fix with other options, run 'go tool fix'.

See also: go fmt, go vet.

Gofmt (reformat) package sources

Usage:

go fmt [-n] [-x] [packages]

Fmt runs the command 'gofmt -l -w' on the packages namedby the import paths. It prints the names of the files that are modified.

For more about gofmt, see 'go doc cmd/gofmt'.For more about specifying packages, see 'go help packages'.

The -n flag prints commands that would be executed.The -x flag prints commands as they are executed.

The -mod flag's value sets which module download modeto use: readonly or vendor. See 'go help modules' for more.

To run gofmt with specific options, run gofmt itself.

See also: go fix, go vet.

Generate Go files by processing source

Usage:

go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

Generate runs commands described by directives within existingfiles. Those commands can run any process but the intent is tocreate or update Go source files.

Go generate is never run automatically by go build, go test,and so on. It must be run explicitly.

Go generate scans the file for directives, which are lines ofthe form,

//go:generate command argument...

(note: no leading spaces and no space in "//go") where commandis the generator to be run, corresponding to an executable filethat can be run locally. It must either be in the shell path(gofmt), a fully qualified path (/usr/you/bin/mytool), or acommand alias, described below.

Note that go generate does not parse the file, so lines that looklike directives in comments or multiline strings will be treatedas directives.

The arguments to the directive are space-separated tokens ordouble-quoted strings passed to the generator as individualarguments when it is run.

Quoted strings use Go syntax and are evaluated before execution; aquoted string appears as a single argument to the generator.

To convey to humans and machine tools that code is generated,generated source should have a line that matches the followingregular expression (in Go syntax):

^// Code generated .* DO NOT EDIT\.$

This line must appear before the first non-comment, non-blanktext in the file.

Go generate sets several variables when it runs the generator:

$GOARCHThe execution architecture (arm, amd64, etc.)$GOOSThe execution operating system (linux, windows, etc.)$GOFILEThe base name of the file.$GOLINEThe line number of the directive in the source file.$GOPACKAGEThe name of the package of the file containing the directive.$GOROOTThe GOROOT directory for the 'go' command that invoked thegenerator, containing the Go toolchain and standard library.$DOLLARA dollar sign.$PATHThe $PATH of the parent process, with $GOROOT/binplaced at the beginning. This causes generatorsthat execute 'go' commands to use the same 'go'as the parent 'go generate' command.

Other than variable substitution and quoted-string evaluation, nospecial processing such as "globbing" is performed on the commandline.

As a last step before running the command, any invocations of anyenvironment variables with alphanumeric names, such as $GOFILE or$HOME, are expanded throughout the command line. The syntax forvariable expansion is $NAME on all operating systems. Due to theorder of evaluation, variables are expanded even inside quotedstrings. If the variable NAME is not set, $NAME expands to theempty string.

A directive of the form,

//go:generate -command xxx args...

specifies, for the remainder of this source file only, that thestring xxx represents the command identified by the arguments. Thiscan be used to create aliases or to handle multiword generators.For example,

//go:generate -command foo go tool foo

specifies that the command "foo" represents the generator"go tool foo".

Generate processes packages in the order given on the command line,one at a time. If the command line lists .go files from a single directory,they are treated as a single package. Within a package, generate processes thesource files in a package in file name order, one at a time. Withina source file, generate runs generators in the order they appearin the file, one at a time. The go generate tool also sets the buildtag "generate" so that files may be examined by go generate but ignoredduring build.

For packages with invalid code, generate processes only source files with avalid package clause.

If any generator returns an error exit status, "go generate" skipsall further processing for that package.

The generator is run in the package's source directory.

Go generate accepts two specific flags:

-run=""if non-empty, specifies a regular expression to selectdirectives whose full original source text (excludingany trailing spaces and final newline) matches theexpression.-skip=""if non-empty, specifies a regular expression to suppressdirectives whose full original source text (excludingany trailing spaces and final newline) matches theexpression. If a directive matches both the -run andthe -skip arguments, it is skipped.

It also accepts the standard build flags including -v, -n, and -x.The -v flag prints the names of packages and files as they areprocessed.The -n flag prints commands that would be executed.The -x flag prints commands as they are executed.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

Add dependencies to current module and install them

Usage:

go get [-t] [-u] [-tool] [build flags] [packages]

Get resolves its command-line arguments to packages at specific module versions,updates go.mod to require those versions, and downloads source code into themodule cache.

To add a dependency for a package or upgrade it to its latest version:

go get example.com/pkg

To upgrade or downgrade a package to a specific version:

go get example.com/pkg@v1.2.3

To remove a dependency on a module and downgrade modules that require it:

go get example.com/mod@none

To upgrade the minimum required Go version to the latest released Go version:

go get go@latest

To upgrade the Go toolchain to the latest patch release of the current Go toolchain:

go get toolchain@patch

Seehttps://golang.org/ref/mod#go-get for details.

In earlier versions of Go, 'go get' was used to build and install packages.Now, 'go get' is dedicated to adjusting dependencies in go.mod. 'go install'may be used to build and install commands instead. When a version is specified,'go install' runs in module-aware mode and ignores the go.mod file in thecurrent directory. For example:

go install example.com/pkg@v1.2.3go install example.com/pkg@latest

See 'go help install' orhttps://golang.org/ref/mod#go-install for details.

'go get' accepts the following flags.

The -t flag instructs get to consider modules needed to build tests ofpackages specified on the command line.

The -u flag instructs get to update modules providing dependenciesof packages named on the command line to use newer minor or patchreleases when available.

The -u=patch flag (not -u patch) also instructs get to update dependencies,but changes the default to select patch releases.

When the -t and -u flags are used together, get will updatetest dependencies as well.

The -tool flag instructs go to add a matching tool line to go.mod for eachlisted package. If -tool is used with @none, the line will be removed.

The -x flag prints commands as they are executed. This is useful fordebugging version control commands when a module is downloaded directlyfrom a repository.

For more about build flags, see 'go help build'.

For more about modules, seehttps://golang.org/ref/mod.

For more about using 'go get' to update the minimum Go version andsuggested Go toolchain, seehttps://go.dev/doc/toolchain.

For more about specifying packages, see 'go help packages'.

See also: go build, go install, go clean, go mod.

Compile and install packages and dependencies

Usage:

go install [build flags] [packages]

Install compiles and installs the packages named by the import paths.

Executables are installed in the directory named by the GOBIN environmentvariable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATHenvironment variable is not set. Executables in $GOROOTare installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN.

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 currentdirectory or any parent directory, if there is one. This is useful forinstalling executables without affecting the dependencies of the main module.To eliminate ambiguity about which module versions are used in the build, thearguments 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), or relative or absolute file paths.

- All arguments must have the same version suffix. Different queries are notallowed, 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 argumentswill only match main packages.

- No module is considered the "main" module. If the module containingpackages named on the command line has a go.mod file, it must not containdirectives (replace and exclude) that would cause it to be interpreteddifferently than if it were the main module. The module must not requirea higher version of itself.

- Vendor directories are not used in any module. (Vendor directories are notincluded in the module zip files downloaded by 'go install'.)

If the arguments don't have version suffixes, "go install" may run inmodule-aware mode or GOPATH mode, depending on the GO111MODULE environmentvariable and the presence of a go.mod file. See 'go help modules' for details.If module-aware mode is enabled, "go install" runs in the context of the mainmodule.

When module-aware mode is disabled, non-main packages are installed in thedirectory $GOPATH/pkg/$GOOS_$GOARCH. When module-aware mode is enabled,non-main packages are built and cached but not installed.

Before Go 1.20, the standard library was installed to$GOROOT/pkg/$GOOS_$GOARCH.Starting in Go 1.20, the standard library is built and cached but not installed.Setting GODEBUG=installgoroot=all restores the use of$GOROOT/pkg/$GOOS_$GOARCH.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

See also: go build, go get, go clean.

List packages or modules

Usage:

go list [-f format] [-json] [-m] [list flags] [build flags] [packages]

List lists the named packages, one per line.The most commonly-used flags are -f and -json, which control the formof the output printed for each package. Other list flags, documented below,control more specific details.

The default output shows the package import path:

bytesencoding/jsongithub.com/gorilla/muxgolang.org/x/net/html

The -f flag specifies an alternate format for the list, using thesyntax of package template. The default output is equivalentto -f '{{.ImportPath}}'. The struct being passed to the template is:

type Package struct {    Dir            string   // directory containing package sources    ImportPath     string   // import path of package in dir    ImportComment  string   // path in import comment on package statement    Name           string   // package name    Doc            string   // package documentation string    Target         string   // install path    Shlib          string   // the shared library that contains this package (only set when -linkshared)    Goroot         bool     // is this package in the Go root?    Standard       bool     // is this package part of the standard Go library?    Stale          bool     // would 'go install' do anything for this package?    StaleReason    string   // explanation for Stale==true    Root           string   // Go root or Go path dir containing this package    ConflictDir    string   // this directory shadows Dir in $GOPATH    BinaryOnly     bool     // binary-only package (no longer supported)    ForTest        string   // package is only for use in named test    Export         string   // file containing export data (when using -export)    BuildID        string   // build ID of the compiled package (when using -export)    Module         *Module  // info about package's containing module, if any (can be nil)    Match          []string // command-line patterns matching this package    DepOnly        bool     // package is only a dependency, not explicitly listed    DefaultGODEBUG string  // default GODEBUG setting, for main packages    // Source files    GoFiles           []string   // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)    CgoFiles          []string   // .go source files that import "C"    CompiledGoFiles   []string   // .go files presented to compiler (when using -compiled)    IgnoredGoFiles    []string   // .go source files ignored due to build constraints    IgnoredOtherFiles []string // non-.go source files ignored due to build constraints    CFiles            []string   // .c source files    CXXFiles          []string   // .cc, .cxx and .cpp source files    MFiles            []string   // .m source files    HFiles            []string   // .h, .hh, .hpp and .hxx source files    FFiles            []string   // .f, .F, .for and .f90 Fortran source files    SFiles            []string   // .s source files    SwigFiles         []string   // .swig files    SwigCXXFiles      []string   // .swigcxx files    SysoFiles         []string   // .syso object files to add to archive    TestGoFiles       []string   // _test.go files in package    XTestGoFiles      []string   // _test.go files outside package    // Embedded files    EmbedPatterns      []string // //go:embed patterns    EmbedFiles         []string // files matched by EmbedPatterns    TestEmbedPatterns  []string // //go:embed patterns in TestGoFiles    TestEmbedFiles     []string // files matched by TestEmbedPatterns    XTestEmbedPatterns []string // //go:embed patterns in XTestGoFiles    XTestEmbedFiles    []string // files matched by XTestEmbedPatterns    // Cgo directives    CgoCFLAGS    []string // cgo: flags for C compiler    CgoCPPFLAGS  []string // cgo: flags for C preprocessor    CgoCXXFLAGS  []string // cgo: flags for C++ compiler    CgoFFLAGS    []string // cgo: flags for Fortran compiler    CgoLDFLAGS   []string // cgo: flags for linker    CgoPkgConfig []string // cgo: pkg-config names    // Dependency information    Imports      []string          // import paths used by this package    ImportMap    map[string]string // map from source import to ImportPath (identity entries omitted)    Deps         []string          // all (recursively) imported dependencies    TestImports  []string          // imports from TestGoFiles    XTestImports []string          // imports from XTestGoFiles    // Error information    Incomplete bool            // this package or a dependency has an error    Error      *PackageError   // error loading package    DepsErrors []*PackageError // errors loading dependencies}

Packages stored in vendor directories report an ImportPath that includes thepath to the vendor directory (for example, "d/vendor/p" instead of "p"),so that the ImportPath uniquely identifies a given copy of a package.The Imports, Deps, TestImports, and XTestImports lists also contain theseexpanded import paths. See golang.org/s/go15vendor for more about vendoring.

The error information, if any, is

type PackageError struct {    ImportStack   []string // shortest path from package named on command line to this one    Pos           string   // position of error (if present, file:line:col)    Err           string   // the error itself}

The module information is a Module struct, defined in the discussionof list -m below.

The template function "join" calls strings.Join.

The template function "context" returns the build context, defined as:

type Context struct {    GOARCH        string   // target architecture    GOOS          string   // target operating system    GOROOT        string   // Go root    GOPATH        string   // Go path    CgoEnabled    bool     // whether cgo can be used    UseAllFiles   bool     // use files regardless of //go:build lines, file names    Compiler      string   // compiler to assume when computing target paths    BuildTags     []string // build constraints to match in //go:build lines    ToolTags      []string // toolchain-specific build constraints    ReleaseTags   []string // releases the current release is compatible with    InstallSuffix string   // suffix to use in the name of the install dir}

For more information about the meaning of these fields see the documentationfor the go/build package's Context type.

The -json flag causes the package data to be printed in JSON formatinstead of using the template format. The JSON flag can optionally beprovided with a set of comma-separated required field names to be output.If so, those required fields will always appear in JSON output, butothers may be omitted to save work in computing the JSON struct.

The -compiled flag causes list to set CompiledGoFiles to the Go sourcefiles presented to the compiler. Typically this means that it repeatsthe files listed in GoFiles and then also adds the Go code generatedby processing CgoFiles and SwigFiles. The Imports list contains theunion of all imports from both GoFiles and CompiledGoFiles.

The -deps flag causes list to iterate over not just the named packagesbut also all their dependencies. It visits them in a depth-first post-ordertraversal, so that a package is listed only after all its dependencies.Packages not explicitly listed on the command line will have the DepOnlyfield set to true.

The -e flag changes the handling of erroneous packages, those thatcannot be found or are malformed. By default, the list commandprints an error to standard error for each erroneous package andomits the packages from consideration during the usual printing.With the -e flag, the list command never prints errors to standarderror and instead processes the erroneous packages with the usualprinting. Erroneous packages will have a non-empty ImportPath anda non-nil Error field; other information may or may not be missing(zeroed).

The -export flag causes list to set the Export field to the name of afile containing up-to-date export information for the given package,and the BuildID field to the build ID of the compiled package.

The -find flag causes list to identify the named packages but notresolve their dependencies: the Imports and Deps lists will be empty.With the -find flag, the -deps, -test and -export commands cannot beused.

The -test flag causes list to report not only the named packagesbut also their test binaries (for packages with tests), to convey tosource code analysis tools exactly how test binaries are constructed.The reported import path for a test binary is the import path ofthe package followed by a ".test" suffix, as in "math/rand.test".When building a test, it is sometimes necessary to rebuild certaindependencies specially for that test (most commonly the testedpackage itself). The reported import path of a package recompiledfor a particular test binary is followed by a space and the name ofthe test binary in brackets, as in "math/randmath/rand.test"or "regexp [sort.test]". The ForTest field is also set to the nameof the package being tested ("math/rand" or "sort" in the previousexamples).

The Dir, Target, Shlib, Root, ConflictDir, and Export file pathsare all absolute paths.

By default, the lists GoFiles, CgoFiles, and so on hold names of files in Dir(that is, paths relative to Dir, not absolute paths).The generated files added when using the -compiled and -test flagsare absolute paths referring to cached copies of generated Go source files.Although they are Go source files, the paths may not end in ".go".

The -m flag causes list to list modules instead of packages.

When listing modules, the -f flag still specifies a format templateapplied to a Go struct, but now a Module struct:

type Module struct {    Path       string        // module path    Query      string        // version query corresponding to this version    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    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}type ModuleError struct {    Err string // the error itself}

The file GoMod refers to may be outside the module directory if themodule is in the module cache or if the -modfile flag is used.

The default output is to print the module path and theninformation about the version and replacement if any.For example, 'go list -m all' might print:

my/main/modulegolang.org/x/text v0.3.0 => /tmp/textrsc.io/pdf v0.1.1

The Module struct has a String method that formats thisline of output, so that the default format is equivalentto -f '{{.String}}'.

Note that when a module has been replaced, its Replace fielddescribes the replacement module, and its Dir field is set tothe replacement's source code, if present. (That is, if Replaceis non-nil, then Dir is set to Replace.Dir, with no access tothe replaced source code.)

The -u flag adds information about available upgrades.When the latest version of a given module is newer thanthe current one, list -u sets the Module's Update fieldto information about the newer module. list -u will also setthe module's Retracted field if the current version is retracted.The Module's String method indicates an available upgrade byformatting the newer version in brackets after the current version.If a version is retracted, the string "(retracted)" will follow it.For example, 'go list -m -u all' might print:

my/main/modulegolang.org/x/text v0.3.0 [v0.4.0] => /tmp/textrsc.io/pdf v0.1.1 (retracted) [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 fieldto a list of all known versions of that module, ordered accordingto semantic versioning, earliest to latest. The flag also changesthe default output format to display the module path followed by thespace-separated version list.

The -retracted flag causes list to report information about retractedmodule versions. When -retracted is used with -f or -json, the Retractedfield explains why the version was retracted.The strings are taken from comments on the retract directive in themodule's go.mod file. When -retracted is used with -versions, retractedversions are listed together with unretracted versions. The -retractedflag may be used with or without -m.

The arguments to list -m are interpreted as a list of modules, not packages.The main module is the module containing the current directory.The active modules are the main module and its dependencies.With no arguments, list -m shows the main module.With arguments, list -m shows the modules specified by the arguments.Any of the active modules can be specified by its module path.The special pattern "all" specifies all the active modules, first the mainmodule and then dependencies sorted by module path.A pattern containing "..." specifies the active modules whosemodule paths match the pattern.A query of the form path@version specifies the result of that query,which is not limited to active modules.See 'go help modules' for more about module queries.

The template function "module" takes a single string argumentthat must be a module path or query and returns the specifiedmodule as a Module struct. If an error occurs, the result willbe a Module struct with a non-nil Error field.

When using -m, the -reuse=old.json flag accepts the name of file containingthe JSON output of a previous 'go list -m -json' invocation with thesame set of modifier flags (such as -u, -retracted, and -versions).The go command may use this file to determine that a module is unchangedsince the previous invocation and avoid redownloading information about it.Modules that are not redownloaded will be marked in the new output bysetting the Reuse field to true. Normally the module cache provides thiskind of reuse automatically; the -reuse flag can be useful on systems thatdo not preserve the module cache.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

For more about modules, seehttps://golang.org/ref/mod.

Module maintenance

Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,not just 'go mod'. For example, day-to-day adding, removing, upgrading,and downgrading of dependencies should be done using 'go get'.See 'go help modules' for an overview of module functionality.

Usage:

go mod <command> [arguments]

The commands are:

download    download modules to local cacheedit        edit go.mod from tools or scriptsgraph       print module requirement graphinit        initialize new module in current directorytidy        add missing and remove unused modulesvendor      make vendored copy of dependenciesverify      verify dependencies have expected contentwhy         explain why packages or modules are needed

Use "go help mod <command>" for more information about a command.

Download modules to local cache

Usage:

go mod download [-x] [-json] [-reuse=old.json] [modules]

Download downloads the named modules, which can be module patterns selectingdependencies of the main module or module queries of the form path@version.

With no arguments, download applies to the modules needed to build and testthe packages in the main module: the modules explicitly required by the mainmodule if it is at 'go 1.17' or higher, or all transitively-required modulesif at 'go 1.16' or lower.

The go command will automatically download modules as needed during ordinaryexecution. The "go mod download" command is useful mainly for pre-fillingthe local cache or to compute the answers for a Go module proxy.

By default, download writes nothing to standard output. It may print progressmessages and errors to standard error.

The -json flag causes download to print a sequence of JSON objectsto 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 -reuse flag accepts the name of file containing the JSON output of aprevious 'go mod download -json' invocation. The go command may use thisfile to determine that a module is unchanged since the previous invocationand avoid redownloading it. Modules that are not redownloaded will be markedin the new output by setting the Reuse field to true. Normally the modulecache provides this kind of reuse automatically; the -reuse flag can beuseful on systems that do not preserve the module cache.

The -x flag causes download to print the commands download executes.

Seehttps://golang.org/ref/mod#go-mod-download for more about 'go mod download'.

Seehttps://golang.org/ref/mod#version-queries for more about version queries.

Edit go.mod from tools or scripts

Usage:

go mod edit [editing flags] [-fmt|-print|-json] [go.mod]

Edit provides a command-line interface for editing go.mod,for use primarily by tools or scripts. It reads only go.mod;it does not look up information about the modules involved.By default, 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 -fmt flag reformats the go.mod file without making other changes.This reformatting is also implied by any other modifications that use orrewrite the go.mod file. The only time this flag is needed is if no otherflags are specified, as in 'go mod edit -fmt'.

The -module flag changes the module's path (the go.mod file's module line).

The -godebug=key=value flag adds a godebug key=value line,replacing any existing godebug lines with the given key.

The -dropgodebug=key flag drops any existing godebug lineswith the given key.

The -require=path@version and -droprequire=path flagsadd 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 satisfyconstraints imposed by other modules.

The -go=version flag sets the expected Go language version.This flag is mainly for tools that understand Go version dependencies.Users should prefer 'go get go@version'.

The -toolchain=version flag sets the Go toolchain to use.This flag is mainly for tools that understand Go version dependencies.Users should prefer 'go get toolchain@version'.

The -exclude=path@version and -dropexclude=path@version flagsadd 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 givenmodule path and version pair. If the @v in old@v is omitted, areplacement without a version on the left side is added, which appliesto 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 modulepath. Note that -replace overrides any redundant replacements for old[@v],so omitting @v will drop existing replacements for specific versions.

The -dropreplace=old[@v] flag drops a replacement of the givenmodule path and version pair. If the @v is omitted, a replacement withouta version on the left side is dropped.

The -retract=version and -dropretract=version flags add and drop aretraction on the given version. The version may be a single versionlike "v1.2.3" or a closed interval like "[v1.1.0,v1.1.9]". Note that-retract=version is a no-op if that retraction already exists.

The -tool=path and -droptool=path flags add and drop a tool declarationfor the given path.

The -ignore=path and -dropignore=path flags add and drop a ignore declarationfor the given path.

The -godebug, -dropgodebug, -require, -droprequire, -exclude, -dropexclude,-replace, -dropreplace, -retract, -dropretract, -tool, -droptool, -ignore,and -dropignore editing flags may be repeated, and the changes are appliedin the order given.

The -print flag prints the final go.mod in its text format instead ofwriting it back to go.mod.

The -json flag prints the final go.mod file in JSON format instead ofwriting it back to go.mod. The JSON output corresponds to these Go types:

type Module struct {Path    stringVersion string}type GoMod struct {Module    ModPathGo        stringToolchain stringGodebug   []GodebugRequire   []RequireExclude   []ModuleReplace   []ReplaceRetract   []Retract}type ModPath struct {Path       stringDeprecated string}type Godebug struct {Key   stringValue string}type Require struct {Path     stringVersion  stringIndirect bool}type Replace struct {Old ModuleNew Module}type Retract struct {Low       stringHigh      stringRationale string}type Tool struct {Path string}type Ignore struct {Path string}

Retract entries representing a single version (not an interval) will havethe "Low" and "High" fields set to the same value.

Note that this only describes the go.mod file itself, not other modulesreferred to indirectly. For the full set of modules available to a build,use 'go list -m -json all'.

Edit also provides the -C, -n, and -x build flags.

Seehttps://golang.org/ref/mod#go-mod-edit for more about 'go mod edit'.

Print module requirement graph

Usage:

go mod graph [-go=version] [-x]

Graph prints the module requirement graph (with replacements applied)in text form. Each line in the output has two space-separated fields: a moduleand one of its requirements. Each module is identified as a string of the formpath@version, except for the main module, which has no @version suffix.

The -go flag causes graph to report the module graph as loaded by thegiven Go version, instead of the version indicated by the 'go' directivein the go.mod file.

The -x flag causes graph to print the commands graph executes.

Seehttps://golang.org/ref/mod#go-mod-graph for more about 'go mod graph'.

Initialize new module in current directory

Usage:

go mod init [module-path]

Init initializes and writes a new go.mod file in the current directory, ineffect creating a new module rooted at the current directory. The go.mod filemust not already exist.

Init accepts one optional argument, the module path for the new module. If themodule path argument is omitted, init will attempt to infer the module pathusing import comments in .go files and the current directory (if in GOPATH).

Seehttps://golang.org/ref/mod#go-mod-init for more about 'go mod init'.

Add missing and remove unused modules

Usage:

go mod tidy [-e] [-v] [-x] [-diff] [-go=version] [-compat=version]

Tidy makes sure go.mod matches the source code in the module.It adds any missing modules necessary to build the current module'spackages and dependencies, and it removes unused modules thatdon't provide any relevant packages. It also adds any missing entriesto go.sum and removes any unnecessary ones.

The -v flag causes tidy to print information about removed modulesto standard error.

The -e flag causes tidy to attempt to proceed despite errorsencountered while loading packages.

The -diff flag causes tidy not to modify go.mod or go.sum butinstead print the necessary changes as a unified diff. It exitswith a non-zero code if the diff is not empty.

The -go flag causes tidy to update the 'go' directive in the go.modfile to the given version, which may change which module dependenciesare retained as explicit requirements in the go.mod file.(Go versions 1.17 and higher retain more requirements in order tosupport lazy module loading.)

The -compat flag preserves any additional checksums needed for the'go' command from the indicated major Go release to successfully loadthe module graph, and causes tidy to error out if that version of the'go' command would load any imported package from a different moduleversion. By default, tidy acts as if the -compat flag were set to theversion prior to the one indicated by the 'go' directive in the go.modfile.

The -x flag causes tidy to print the commands download executes.

Seehttps://golang.org/ref/mod#go-mod-tidy for more about 'go mod tidy'.

Make vendored copy of dependencies

Usage:

go mod vendor [-e] [-v] [-o outdir]

Vendor resets the main module's vendor directory to include all packagesneeded to build and test all the main module's packages.It does not include test code for vendored packages.

The -v flag causes vendor to print the names of vendoredmodules and packages to standard error.

The -e flag causes vendor to attempt to proceed despite errorsencountered while loading packages.

The -o flag causes vendor to create the vendor directory at the givenpath instead of "vendor". The go command can only use a vendor directorynamed "vendor" within the module root directory, so this flag isprimarily useful for other tools.

Seehttps://golang.org/ref/mod#go-mod-vendor for more about 'go mod vendor'.

Verify dependencies have expected content

Usage:

go mod verify

Verify checks that the dependencies of the current module,which are stored in a local downloaded source cache, have not beenmodified since being downloaded. If all the modules are unmodified,verify prints "all modules verified." Otherwise it reports whichmodules have been changed and causes 'go mod' to exit with anon-zero status.

Seehttps://golang.org/ref/mod#go-mod-verify for more about 'go mod verify'.

Explain why packages or modules are needed

Usage:

go mod why [-m] [-vendor] packages...

Why shows a shortest path in the import graph from the main module toeach of the listed packages. If the -m flag is given, why treats thearguments as a list of modules and finds a path to any package in eachof the modules.

By default, why queries the graph of packages matched by "go list all",which includes tests for reachable packages. The -vendor flag causes whyto exclude tests of dependencies.

The output is a sequence of stanzas, one for each package or modulename on the command line, separated by blank lines. Each stanza beginswith a comment line "# package" or "# module" giving the targetpackage or module. Subsequent lines give a path through the importgraph, one package per line. If the package or module is notreferenced from the main module, the stanza will display a singleparenthesized note indicating that fact.

For example:

$ go mod why golang.org/x/text/language golang.org/x/text/encoding# golang.org/x/text/languagersc.io/quotersc.io/samplergolang.org/x/text/language# golang.org/x/text/encoding(main module does not need package golang.org/x/text/encoding)$

Seehttps://golang.org/ref/mod#go-mod-why for more about 'go mod why'.

Workspace maintenance

Work provides access to operations on workspaces.

Note that support for workspaces is built into many other commands, notjust 'go work'.

See 'go help modules' for information about Go's module system of whichworkspaces are a part.

Seehttps://go.dev/ref/mod#workspaces for an in-depth reference onworkspaces.

Seehttps://go.dev/doc/tutorial/workspaces for an introductorytutorial on workspaces.

A workspace is specified by a go.work file that specifies a set ofmodule directories with the "use" directive. These modules are used asroot modules by the go command for builds and related operations. Aworkspace that does not specify modules to be used cannot be used to dobuilds from local modules.

go.work files are line-oriented. Each line holds a single directive,made up of a keyword followed by arguments. For example:

go 1.18use ../foo/baruse ./bazreplace example.com/foo v1.2.3 => example.com/bar v1.4.5

The leading keyword can be factored out of adjacent lines to create a block,like in Go imports.

use (  ../foo/bar  ./baz)

The use directive specifies a module to be included in the workspace'sset of main modules. The argument to the use directive is the directorycontaining the module's go.mod file.

The go directive specifies the version of Go the file was written at. Itis possible there may be future changes in the semantics of workspacesthat could be controlled by this version, but for now the versionspecified has no effect.

The replace directive has the same syntax as the replace directive in ago.mod file and takes precedence over replaces in go.mod files. It isprimarily intended to override conflicting replaces in different workspacemodules.

To determine whether the go command is operating in workspace mode, usethe "go env GOWORK" command. This will specify the workspace file beingused.

Usage:

go work <command> [arguments]

The commands are:

edit        edit go.work from tools or scriptsinit        initialize workspace filesync        sync workspace build list to modulesuse         add modules to workspace filevendor      make vendored copy of dependencies

Use "go help work <command>" for more information about a command.

Edit go.work from tools or scripts

Usage:

go work edit [editing flags] [go.work]

Edit provides a command-line interface for editing go.work,for use primarily by tools or scripts. It only reads go.work;it does not look up information about the modules involved.If no file is specified, Edit looks for a go.work file in the currentdirectory and its parent directories

The editing flags specify a sequence of editing operations.

The -fmt flag reformats the go.work file without making other changes.This reformatting is also implied by any other modifications that use orrewrite the go.mod file. The only time this flag is needed is if no otherflags are specified, as in 'go work edit -fmt'.

The -godebug=key=value flag adds a godebug key=value line,replacing any existing godebug lines with the given key.

The -dropgodebug=key flag drops any existing godebug lineswith the given key.

The -use=path and -dropuse=path flagsadd and drop a use directive from the go.work file's set of module directories.

The -replace=old[@v]=new[@v] flag adds a replacement of the givenmodule path and version pair. If the @v in old@v is omitted, areplacement without a version on the left side is added, which appliesto 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 modulepath. Note that -replace overrides any redundant replacements for old[@v],so omitting @v will drop existing replacements for specific versions.

The -dropreplace=old[@v] flag drops a replacement of the givenmodule path and version pair. If the @v is omitted, a replacement withouta version on the left side is dropped.

The -use, -dropuse, -replace, and -dropreplace,editing flags may be repeated, and the changes are applied in the order given.

The -go=version flag sets the expected Go language version.

The -toolchain=name flag sets the Go toolchain to use.

The -print flag prints the final go.work in its text format instead ofwriting it back to go.mod.

The -json flag prints the final go.work file in JSON format instead ofwriting it back to go.mod. The JSON output corresponds to these Go types:

type GoWork struct {Go        stringToolchain stringGodebug   []GodebugUse       []UseReplace   []Replace}type Godebug struct {Key   stringValue string}type Use struct {DiskPath   stringModulePath string}type Replace struct {Old ModuleNew Module}type Module struct {Path    stringVersion string}

See the workspaces reference athttps://go.dev/ref/mod#workspacesfor more information.

Initialize workspace file

Usage:

go work init [moddirs]

Init initializes and writes a new go.work file in thecurrent directory, in effect creating a new workspace at the currentdirectory.

go work init optionally accepts paths to the workspace modules asarguments. If the argument is omitted, an empty workspace with nomodules will be created.

Each argument path is added to a use directive in the go.work file. Thecurrent go version will also be listed in the go.work file.

See the workspaces reference athttps://go.dev/ref/mod#workspacesfor more information.

Sync workspace build list to modules

Usage:

go work sync

Sync syncs the workspace's build list back to theworkspace's modules

The workspace's build list is the set of versions of all the(transitive) dependency modules used to do builds in the workspace. gowork sync generates that build list using the Minimal Version Selectionalgorithm, and then syncs those versions back to each of modulesspecified in the workspace (with use directives).

The syncing is done by sequentially upgrading each of the dependencymodules specified in a workspace module to the version in the build listif the dependency module's version is not already the same as the buildlist's version. Note that Minimal Version Selection guarantees that thebuild list's version of each module is always the same or higher thanthat in each workspace module.

See the workspaces reference athttps://go.dev/ref/mod#workspacesfor more information.

Add modules to workspace file

Usage:

go work use [-r] [moddirs]

Use provides a command-line interface for addingdirectories, optionally recursively, to a go.work file.

A use directive will be added to the go.work file for each argumentdirectory listed on the command line go.work file, if it exists,or removed from the go.work file if it does not exist.Use fails if any remaining use directives refer to modules thatdo not exist.

Use updates the go line in go.work to specify a version at least asnew as all the go lines in the used modules, both preexisting onesand newly added ones. With no arguments, this update is the onlything that go work use does.

The -r flag searches recursively for modules in the argumentdirectories, and the use command operates as if each of the directorieswere specified as arguments.

See the workspaces reference athttps://go.dev/ref/mod#workspacesfor more information.

Make vendored copy of dependencies

Usage:

go work vendor [-e] [-v] [-o outdir]

Vendor resets the workspace's vendor directory to include all packagesneeded to build and test all the workspace's packages.It does not include test code for vendored packages.

The -v flag causes vendor to print the names of vendoredmodules and packages to standard error.

The -e flag causes vendor to attempt to proceed despite errorsencountered while loading packages.

The -o flag causes vendor to create the vendor directory at the givenpath instead of "vendor". The go command can only use a vendor directorynamed "vendor" within the module root directory, so this flag isprimarily useful for other tools.

Compile and run Go program

Usage:

go run [build flags] [-exec xprog] package [arguments...]

Run compiles and runs the named main Go package.Typically the package is specified as a list of .go source files from a singledirectory, but it may also be an import path, file system path, or patternmatching a single known package, as in 'go run .' or 'go run my/cmd'.

If the package argument has a version suffix (like @latest or @v1.0.0),"go run" builds the program in module-aware mode, ignoring the go.mod file inthe current directory or any parent directory, if there is one. This is usefulfor running programs without affecting the dependencies of the main module.

If the package argument doesn't have a version suffix, "go run" may run inmodule-aware mode or GOPATH mode, depending on the GO111MODULE environmentvariable and the presence of a go.mod file. See 'go help modules' for details.If module-aware mode is enabled, "go run" runs in the context of the mainmodule.

By default, 'go run' runs the compiled binary directly: 'a.out arguments...'.If the -exec flag is given, 'go run' invokes the binary using xprog:

'xprog a.out arguments...'.

If the -exec flag is not given, GOOS or GOARCH is different from the systemdefault, and a program named go_$GOOS_$GOARCH_exec can be foundon the current search path, 'go run' invokes the binary using that program,for example 'go_js_wasm_exec a.out arguments...'. This allows execution ofcross-compiled programs when a simulator or other execution method isavailable.

By default, 'go run' compiles the binary without generating the informationused by debuggers, to reduce build time. To include debugger information inthe binary, use 'go build'.

The exit status of Run is not the exit status of the compiled binary.

For more about build flags, see 'go help build'.For more about specifying packages, see 'go help packages'.

See also: go build.

Manage telemetry data and settings

Usage:

go telemetry [off|local|on]

Telemetry is used to manage Go telemetry data and settings.

Telemetry can be in one of three modes: off, local, or on.

When telemetry is in local mode, counter data is written to the local filesystem, but will not be uploaded to remote servers.

When telemetry is off, local counter data is neither collected nor uploaded.

When telemetry is on, telemetry data is written to the local file systemand periodically sent tohttps://telemetry.go.dev/. Uploaded data is used tohelp improve the Go toolchain and related tools, and it will be published aspart of a public dataset.

For more details, seehttps://telemetry.go.dev/privacy.This data is collected in accordance with the Google Privacy Policy(https://policies.google.com/privacy).

To view the current telemetry mode, run "go telemetry".To disable telemetry uploading, but keep local data collection, run"go telemetry local".To enable both collection and uploading, run “go telemetry on”.To disable both collection and uploading, run "go telemetry off".

The current telemetry mode is also available as the value of thenon-settable "GOTELEMETRY" go env variable. The directory in thelocal file system that telemetry data is written to is availableas the value of the non-settable "GOTELEMETRYDIR" go env variable.

Seehttps://go.dev/doc/telemetry for more information on telemetry.

Test packages

Usage:

go test [build/test flags] [packages] [build/test flags & test binary flags]

'Go test' automates testing the packages named by the import paths.It prints a summary of the test results in the format:

ok   archive/tar   0.011sFAIL archive/zip   0.022sok   compress/gzip 0.033s...

followed by detailed output for each failed package.

'Go test' recompiles each package along with any files with names matchingthe file pattern "*_test.go".These additional files can contain test functions, benchmark functions, fuzztests and example functions. See 'go help testfunc' for more.Each listed package causes the execution of a separate test binary.Files whose names begin with "_" (including "_test.go") or "." are ignored.

Test files that declare a package with the suffix "_test" will be compiled as aseparate package, and then linked and run with the main test binary.

The go tool will ignore a directory named "testdata", making it availableto hold ancillary data needed by the tests.

As part of building a test binary, go test runs go vet on the packageand its test source files to identify significant problems. If go vetfinds any problems, go test reports those and does not run the testbinary. Only a high-confidence subset of the default go vet checks areused. That subset is: atomic, bool, buildtags, directive, errorsas,ifaceassert, nilfunc, printf, stringintconv, and tests. You can seethe documentation for these and other vet tests via "go doc cmd/vet".To disable the running of go vet, use the -vet=off flag. To run allchecks, use the -vet=all flag.

All test output and summary lines are printed to the go command'sstandard output, even if the test printed them to its own standarderror. (The go command's standard error is reserved for printingerrors building the tests.)

The go command places $GOROOT/bin at the beginning of $PATHin the test's environment, so that tests that execute'go' commands use the same 'go' as the parent 'go test' command.

Go test runs in two different modes:

The first, called local directory mode, occurs when go test isinvoked with no package arguments (for example, 'go test' or 'gotest -v'). In this mode, go test compiles the package sources andtests found in the current directory and then runs the resultingtest binary. In this mode, caching (discussed below) is disabled.After the package test finishes, go test prints a summary lineshowing the test status ('ok' or 'FAIL'), package name, and elapsedtime.

The second, called package list mode, occurs when go test is invokedwith explicit package arguments (for example 'go test math', 'gotest ./...', and even 'go test .'). In this mode, go test compilesand tests each of the packages listed on the command line. If apackage test passes, go test prints only the final 'ok' summaryline. If a package test fails, go test prints the full test output.If invoked with the -bench or -v flag, go test prints the fulloutput even for passing package tests, in order to display therequested benchmark results or verbose logging. After the packagetests for all of the listed packages finish, and their output isprinted, go test prints a final 'FAIL' status if any package testhas failed.

In package list mode only, go test caches successful package testresults to avoid unnecessary repeated running of tests. When theresult of a test can be recovered from the cache, go test willredisplay the previous output instead of running the test binaryagain. When this happens, go test prints '(cached)' in place of theelapsed time in the summary line.

The rule for a match in the cache is that the run involves the sametest binary and the flags on the command line come entirely from arestricted set of 'cacheable' test flags, defined as -benchtime,-coverprofile, -cpu, -failfast, -fullpath, -list, -outputdir, -parallel,-run, -short, -skip, -timeout and -v.If a run of go test has any test or non-test flags outside this set,the result is not cached. To disable test caching, use any test flagor argument other than the cacheable flags. The idiomatic way to disabletest caching explicitly is to use -count=1. Tests that open files withinthe package's module or that consult environment variables onlymatch future runs in which the files and environment variables areunchanged. A cached test result is treated as executing in no timeat all, so a successful package test result will be cached andreused regardless of -timeout setting.

In addition to the build flags, the flags handled by 'go test' itself are:

-args    Pass the remainder of the command line (everything after -args)    to the test binary, uninterpreted and unchanged.    Because this flag consumes the remainder of the command line,    the package list (if present) must appear before this flag.-c    Compile the test binary to pkg.test in the current directory but do not run it    (where pkg is the last element of the package's import path).    The file name or target directory can be changed with the -o flag.-exec xprog    Run the test binary using xprog. The behavior is the same as    in 'go run'. See 'go help run' for details.-json    Convert test output to JSON suitable for automated processing.    See 'go doc test2json' for the encoding details.    Also emits build output in JSON. See 'go help buildjson'.-o file    Compile the test binary to the named file.    The test still runs (unless -c or -i is specified).    If file ends in a slash or names an existing directory,    the test is written to pkg.test in that directory.

The test binary also accepts flags that control execution of the test; theseflags are also accessible by 'go test'. See 'go help testflag' for details.

For more about build flags, see 'go help build'.For more about specifying packages, see 'go help packages'.

See also: go build, go vet.

Run specified go tool

Usage:

go tool [-n] command [args...]

Tool runs the go tool command identified by the arguments.

Go ships with a number of builtin tools, and additional toolsmay be defined in the go.mod of the current module.

With no arguments it prints the list of known tools.

The -n flag causes tool to print the command that would beexecuted but not execute it.

The -modfile=file.mod build flag causes tool to use an alternate fileinstead of the go.mod in the module root directory.

Tool also provides the -C, -overlay, and -modcacherw build flags.

For more about build flags, see 'go help build'.

For more about each builtin tool command, see 'go doc cmd/<command>'.

Print Go version

Usage:

go version [-m] [-v] [-json] [file ...]

Version prints the build information for Go binary files.

Go version reports the Go version used to build each of the named files.

If no files are named on the command line, go version prints its ownversion 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 foundduring a directory scan. The -v flag causes it to report unrecognized files.

The -m flag causes go version to print each file's embeddedmodule version information, when available. In the output, the moduleinformation consists of multiple lines following the version line, eachindented by a leading tab character.

The -json flag is similar to -m but outputs the runtime/debug.BuildInfo in JSON format.If flag -json is specified without -m, go version reports an error.

See also: go doc runtime/debug.BuildInfo.

Report likely mistakes in packages

Usage:

go vet [build flags] [-vettool prog] [vet flags] [packages]

Vet runs the Go vet command on the packages named by the import paths.

For more about vet and its flags, see 'go doc cmd/vet'.For more about specifying packages, see 'go help packages'.For a list of checkers and their flags, see 'go tool vet help'.For details of a specific checker such as 'printf', see 'go tool vet help printf'.

The -vettool=prog flag selects a different analysis tool with alternativeor additional checks.For example, the 'shadow' analyzer can be built and run using these commands:

go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latestgo vet -vettool=$(which shadow)

The build flags supported by go vet are those that control package resolutionand execution, such as -C, -n, -x, -v, -tags, and -toolexec.For more about these flags, see 'go help build'.

See also: go fmt, go fix.

Build constraints

A build constraint, also known as a build tag, is a condition under which afile should be included in the package. Build constraints are given by aline comment that begins

//go:build

Build constraints can also be used to downgrade the language versionused to compile a file.

Constraints may appear in any kind of source file (not just Go), butthey must appear near the top of the file, precededonly by blank lines and other comments. These rules mean that in Gofiles a build constraint must appear before the package clause.

To distinguish build constraints from package documentation,a build constraint should be followed by a blank line.

A build constraint comment is evaluated as an expression containingbuild tags combined by ||, &&, and ! operators and parentheses.Operators have the same meaning as in Go.

For example, the following build constraint constrains a file tobuild when the "linux" and "386" constraints are satisfied, or when"darwin" is satisfied and "cgo" is not:

//go:build (linux && 386) || (darwin && !cgo)

It is an error for a file to have more than one //go:build line.

During a particular build, the following build tags are satisfied:

  • the target operating system, as spelled by runtime.GOOS, set with theGOOS environment variable.
  • the target architecture, as spelled by runtime.GOARCH, set with theGOARCH environment variable.
  • any architecture features, in the form GOARCH.feature(for example, "amd64.v2"), as detailed below.
  • "unix", if GOOS is a Unix or Unix-like system.
  • the compiler being used, either "gc" or "gccgo"
  • "cgo", if the cgo command is supported (see CGO_ENABLED in'go help environment').
  • a term for each Go major release, through the current version:"go1.1" from Go version 1.1 onward, "go1.12" from Go 1.12, and so on.
  • any additional tags given by the -tags flag (see 'go help build').

There are no separate build tags for beta or minor releases.

If a file's name, after stripping the extension and a possible _test suffix,matches any of the following patterns:

*_GOOS*_GOARCH*_GOOS_GOARCH

(example: source_windows_amd64.go) where GOOS and GOARCH representany known operating system and architecture values respectively, thenthe file is considered to have an implicit build constraint requiringthose terms (in addition to any explicit constraints in the file).

Using GOOS=android matches build tags and files as for GOOS=linuxin addition to android tags and files.

Using GOOS=illumos matches build tags and files as for GOOS=solarisin addition to illumos tags and files.

Using GOOS=ios matches build tags and files as for GOOS=darwinin addition to ios tags and files.

The defined architecture feature build tags are:

  • For GOARCH=386, GO386=387 and GO386=sse2set the 386.387 and 386.sse2 build tags, respectively.
  • For GOARCH=amd64, GOAMD64=v1, v2, and v3correspond to the amd64.v1, amd64.v2, and amd64.v3 feature build tags.
  • For GOARCH=arm, GOARM=5, 6, and 7correspond to the arm.5, arm.6, and arm.7 feature build tags.
  • For GOARCH=arm64, GOARM64=v8.{0-9} and v9.{0-5}correspond to the arm64.v8.{0-9} and arm64.v9.{0-5} feature build tags.
  • For GOARCH=mips or mipsle,GOMIPS=hardfloat and softfloatcorrespond to the mips.hardfloat and mips.softfloat(or mipsle.hardfloat and mipsle.softfloat) feature build tags.
  • For GOARCH=mips64 or mips64le,GOMIPS64=hardfloat and softfloatcorrespond to the mips64.hardfloat and mips64.softfloat(or mips64le.hardfloat and mips64le.softfloat) feature build tags.
  • For GOARCH=ppc64 or ppc64le,GOPPC64=power8, power9, and power10 correspond to theppc64.power8, ppc64.power9, and ppc64.power10(or ppc64le.power8, ppc64le.power9, and ppc64le.power10)feature build tags.
  • For GOARCH=riscv64,GORISCV64=rva20u64, rva22u64 and rva23u64 correspond to the riscv64.rva20u64,riscv64.rva22u64 and riscv64.rva23u64 build tags.
  • For GOARCH=wasm, GOWASM=satconv and signextcorrespond to the wasm.satconv and wasm.signext feature build tags.

For GOARCH=amd64, arm, ppc64, ppc64le, and riscv64, a particular feature levelsets the feature build tags for all previous levels as well.For example, GOAMD64=v2 sets the amd64.v1 and amd64.v2 feature flags.This ensures that code making use of v2 features continues to compilewhen, say, GOAMD64=v4 is introduced.Code handling the absence of a particular feature levelshould use a negation:

//go:build !amd64.v2

To keep a file from being considered for any build:

//go:build ignore

(Any other unsatisfied word will work as well, but "ignore" is conventional.)

To build a file only when using cgo, and only on Linux and OS X:

//go:build cgo && (linux || darwin)

Such a file is usually paired with another file implementing thedefault functionality for other systems, which in this case wouldcarry the constraint:

//go:build !(cgo && (linux || darwin))

Naming a file dns_windows.go will cause it to be included only whenbuilding the package for Windows; similarly, math_386.s will be includedonly when building the package for 32-bit x86.

Go versions 1.16 and earlier used a different syntax for build constraints,with a "// +build" prefix. The gofmt command will add an equivalent //go:buildconstraint when encountering the older syntax.

In modules with a Go version of 1.21 or later, if a file's build constrainthas a term for a Go major release, the language version used when compilingthe file will be the minimum version implied by the build constraint.

Build -json encoding

The 'go build', 'go install', and 'go test' commands take a -json flag thatreports build output and failures as structured JSON output on standardoutput.

The JSON stream is a newline-separated sequence of BuildEvent objectscorresponding to the Go struct:

type BuildEvent struct {ImportPath stringAction     stringOutput     string}

The ImportPath field gives the package ID of the package being built.This matches the Package.ImportPath field of go list -json and theTestEvent.FailedBuild field of go test -json. Note that it does notmatch TestEvent.Package.

The Action field is one of the following:

build-output - The toolchain printed outputbuild-fail - The build failed

The Output field is set for Action == "build-output" and is a portion ofthe build's output. The concatenation of the Output fields of all outputevents is the exact output of the build. A single event may contain oneor more lines of output and there may be more than one output event fora given ImportPath. This matches the definition of the TestEvent.Outputfield produced by go test -json.

For go test -json, this struct is designed so that parsers can distinguishinterleaved TestEvents and BuildEvents by inspecting the Action field.Furthermore, as with TestEvent, parsers can simply concatenate the Outputfields of all events to reconstruct the text format output, as it wouldhave appeared from go build without the -json flag.

Note that there may also be non-JSON error text on standard error, evenwith the -json flag. Typically, this indicates an early, serious error.Consumers should be robust to this.

Build modes

The 'go build' and 'go install' commands take a -buildmode argument whichindicates which kind of object file is to be built. Currently supported valuesare:

-buildmode=archiveBuild the listed non-main packages into .a files. Packages namedmain are ignored.-buildmode=c-archiveBuild the listed main package, plus all packages it imports,into a C archive file. The only callable symbols will be thosefunctions exported using a cgo //export comment. Requiresexactly one main package to be listed.-buildmode=c-sharedBuild the listed main package, plus all packages it imports,into a C shared library. The only callable symbols willbe those functions exported using a cgo //export comment.On wasip1, this mode builds it to a WASI reactor/library,of which the callable symbols are those functions exportedusing a //go:wasmexport directive. Requires exactly onemain package to be listed.-buildmode=defaultListed main packages are built into executables and listednon-main packages are built into .a files (the defaultbehavior).-buildmode=sharedCombine all the listed non-main packages into a single sharedlibrary that will be used when building with the -linksharedoption. Packages named main are ignored.-buildmode=exeBuild the listed main packages and everything they import intoexecutables. Packages not named main are ignored.-buildmode=pieBuild the listed main packages and everything they import intoposition independent executables (PIE). Packages not namedmain are ignored.-buildmode=pluginBuild the listed main packages, plus all packages that theyimport, into a Go plugin. Packages not named main are ignored.

On AIX, when linking a C program that uses a Go archive built with-buildmode=c-archive, you must pass -Wl,-bnoobjreorder to the C compiler.

Calling between Go and C

There are two different ways to call between Go and C/C++ code.

The first is the cgo tool, which is part of the Go distribution. Forinformation on how to use it see the cgo documentation (go doc cmd/cgo).

The second is the SWIG program, which is a general tool forinterfacing between languages. For information on SWIG seehttps://swig.org/. When running go build, any file with a .swigextension will be passed to SWIG. Any file with a .swigcxx extensionwill be passed to SWIG with the -c++ option. A package can't be justa .swig or .swigcxx file; there must be at least one .go file, even ifit has just a package clause.

When either cgo or SWIG is used, go build will pass any .c, .m, .s, .Sor .sx files to the C compiler, and any .cc, .cpp, .cxx files to the C++compiler. The CC or CXX environment variables may be set to determinethe C or C++ compiler, respectively, to use.

Build and test caching

The go command caches build outputs for reuse in future builds.The default location for cache data is a subdirectory named go-buildin the standard user cache directory for the current operating system.The cache is safe for concurrent invocations of the go command.Setting the GOCACHE environment variable overrides this default,and running 'go env GOCACHE' prints the current cache directory.

The go command periodically deletes cached data that has not beenused recently. Running 'go clean -cache' deletes all cached data.

The build cache correctly accounts for changes to Go source files,compilers, compiler options, and so on: cleaning the cache explicitlyshould not be necessary in typical use. However, the build cachedoes not detect changes to C libraries imported with cgo.If you have made changes to the C libraries on your system, youwill need to clean the cache explicitly or else use the -a build flag(see 'go help build') to force rebuilding of packages thatdepend on the updated C libraries.

The go command also caches successful package test results.See 'go help test' for details. Running 'go clean -testcache' removesall cached test results (but not cached build results).

The go command also caches values used in fuzzing with 'go test -fuzz',specifically, values that expanded code coverage when passed to afuzz function. These values are not used for regular building andtesting, but they're stored in a subdirectory of the build cache.Running 'go clean -fuzzcache' removes all cached fuzzing values.This may make fuzzing less effective, temporarily.

The GODEBUG environment variable can enable printing of debugginginformation about the state of the cache:

GODEBUG=gocacheverify=1 causes the go command to bypass theuse of any cache entries and instead rebuild everything and checkthat the results match existing cache entries.

GODEBUG=gocachehash=1 causes the go command to print the inputsfor all of the content hashes it uses to construct cache lookup keys.The output is voluminous but can be useful for debugging the cache.

GODEBUG=gocachetest=1 causes the go command to print details of itsdecisions about whether to reuse a cached test result.

Environment variables

The go command and the tools it invokes consult environment variablesfor configuration. If an environment variable is unset or empty, the gocommand uses a sensible default setting. To see the effective setting ofthe variable <NAME>, run 'go env <NAME>'. To change the default setting,run 'go env -w <NAME>=<VALUE>'. Defaults changed using 'go env -w'are recorded in a Go environment configuration file stored in theper-user configuration directory, as reported by os.UserConfigDir.The location of the configuration file can be changed by settingthe environment variable GOENV, and 'go env GOENV' prints theeffective location, but 'go env -w' cannot change the default location.See 'go help env' for details.

General-purpose environment variables:

GCCGOThe gccgo command to run for 'go build -compiler=gccgo'.GO111MODULEControls whether the go command runs in module-aware mode or GOPATH mode.May be "off", "on", or "auto".See https://golang.org/ref/mod#mod-commands.GOARCHThe architecture, or processor, for which to compile code.Examples are amd64, 386, arm, ppc64.GOAUTHControls authentication for go-import and HTTPS module mirror interactions.See 'go help goauth'.GOBINThe directory where 'go install' will install a command.GOCACHEThe directory where the go command will store cachedinformation for reuse in future builds. Must be an absolute path.GOCACHEPROGA command (with optional space-separated flags) that implements anexternal go command build cache.See 'go doc cmd/go/internal/cacheprog'.GODEBUGEnable various debugging facilities for programs built with Go,including the go command. Cannot be set using 'go env -w'.See https://go.dev/doc/godebug for details.GOENVThe location of the Go environment configuration file.Cannot be set using 'go env -w'.Setting GOENV=off in the environment disables the use of thedefault configuration file.GOFLAGSA space-separated list of -flag=value settings to applyto go commands by default, when the given flag is known bythe current command. Each entry must be a standalone flag.Because the entries are space-separated, flag values mustnot contain spaces. Flags listed on the command lineare applied after this list and therefore override it.GOINSECUREComma-separated list of glob patterns (in the syntax of Go's path.Match)of module path prefixes that should always be fetched in an insecuremanner. Only applies to dependencies that are being fetched directly.GOINSECURE does not disable checksum database validation. GOPRIVATE orGONOSUMDB may be used to achieve that.GOMODCACHEThe directory where the go command will store downloaded modules.GOOSThe operating system for which to compile code.Examples are linux, darwin, windows, netbsd.GOPATHControls where various files are stored. See: 'go help gopath'.GOPRIVATE, GONOPROXY, GONOSUMDBComma-separated list of glob patterns (in the syntax of Go's path.Match)of module path prefixes that should always be fetched directlyor that should not be compared against the checksum database.See https://golang.org/ref/mod#private-modules.GOPROXYURL of Go module proxy. See https://golang.org/ref/mod#environment-variablesand https://golang.org/ref/mod#module-proxy for details.GOROOTThe root of the go tree.GOSUMDBThe name of checksum database to use and optionally its public key andURL. See https://golang.org/ref/mod#authenticating.GOTMPDIRThe directory where the go command will writetemporary source files, packages, and binaries.GOTOOLCHAINControls which Go toolchain is used. See https://go.dev/doc/toolchain.GOVCSLists version control commands that may be used with matching servers.See 'go help vcs'.GOWORKIn module aware mode, use the given go.work file as a workspace file.By default or when GOWORK is "auto", the go command searches for afile named go.work in the current directory and then containing directoriesuntil one is found. If a valid go.work file is found, the modulesspecified will collectively be used as the main modules. If GOWORKis "off", or a go.work file is not found in "auto" mode, workspacemode is disabled.

Environment variables for use with cgo:

ARThe command to use to manipulate library archives whenbuilding with the gccgo compiler.The default is 'ar'.CCThe command to use to compile C code.CGO_CFLAGSFlags that cgo will pass to the compiler when compilingC code.CGO_CFLAGS_ALLOWA regular expression specifying additional flags to allowto appear in #cgo CFLAGS source code directives.Does not apply to the CGO_CFLAGS environment variable.CGO_CFLAGS_DISALLOWA regular expression specifying flags that must be disallowedfrom appearing in #cgo CFLAGS source code directives.Does not apply to the CGO_CFLAGS environment variable.CGO_CPPFLAGS, CGO_CPPFLAGS_ALLOW, CGO_CPPFLAGS_DISALLOWLike CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,but for the C preprocessor.CGO_CXXFLAGS, CGO_CXXFLAGS_ALLOW, CGO_CXXFLAGS_DISALLOWLike CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,but for the C++ compiler.CGO_ENABLEDWhether the cgo command is supported. Either 0 or 1.CGO_FFLAGS, CGO_FFLAGS_ALLOW, CGO_FFLAGS_DISALLOWLike CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,but for the Fortran compiler.CGO_LDFLAGS, CGO_LDFLAGS_ALLOW, CGO_LDFLAGS_DISALLOWLike CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,but for the linker.CXXThe command to use to compile C++ code.FCThe command to use to compile Fortran code.PKG_CONFIGPath to pkg-config tool.

Architecture-specific environment variables:

GO386For GOARCH=386, how to implement floating point instructions.Valid values are sse2 (default), softfloat.GOAMD64For GOARCH=amd64, the microarchitecture level for which to compile.Valid values are v1 (default), v2, v3, v4.See https://golang.org/wiki/MinimumRequirements#amd64GOARMFor GOARCH=arm, the ARM architecture for which to compile.Valid values are 5, 6, 7.When the Go tools are built on an arm system,the default value is set based on what the build system supports.When the Go tools are not built on an arm system(that is, when building a cross-compiler),the default value is 7.The value can be followed by an option specifying how to implement floating point instructions.Valid options are ,softfloat (default for 5) and ,hardfloat (default for 6 and 7).GOARM64For GOARCH=arm64, the ARM64 architecture for which to compile.Valid values are v8.0 (default), v8.{1-9}, v9.{0-5}.The value can be followed by an option specifying extensions implemented by target hardware.Valid options are ,lse and ,crypto.Note that some extensions are enabled by default starting from a certain GOARM64 version;for example, lse is enabled by default starting from v8.1.GOMIPSFor GOARCH=mips{,le}, whether to use floating point instructions.Valid values are hardfloat (default), softfloat.GOMIPS64For GOARCH=mips64{,le}, whether to use floating point instructions.Valid values are hardfloat (default), softfloat.GOPPC64For GOARCH=ppc64{,le}, the target ISA (Instruction Set Architecture).Valid values are power8 (default), power9, power10.GORISCV64For GOARCH=riscv64, the RISC-V user-mode application profile for whichto compile. Valid values are rva20u64 (default), rva22u64, rva23u64.See https://github.com/riscv/riscv-profiles/blob/main/src/profiles.adocand https://github.com/riscv/riscv-profiles/blob/main/src/rva23-profile.adocGOWASMFor GOARCH=wasm, comma-separated list of experimental WebAssembly features to use.Valid values are satconv, signext.

Environment variables for use with code coverage:

GOCOVERDIRDirectory into which to write code coverage data filesgenerated by running a "go build -cover" binary.

Special-purpose environment variables:

GCCGOTOOLDIRIf set, where to find gccgo tools, such as cgo.The default is based on how gccgo was configured.GOEXPERIMENTComma-separated list of toolchain experiments to enable or disable.The list of available experiments may change arbitrarily over time.See GOROOT/src/internal/goexperiment/flags.go for currently valid values.Warning: This variable is provided for the development and testingof the Go toolchain itself. Use beyond that purpose is unsupported.GOFIPS140The FIPS-140 cryptography mode to use when building binaries.The default is GOFIPS140=off, which makes no FIPS-140 changes at all.Other values enable FIPS-140 compliance measures and select alternateversions of the cryptography source code.See https://go.dev/security/fips140 for details.GO_EXTLINK_ENABLEDWhether the linker should use external linking modewhen using -linkmode=auto with code that uses cgo.Set to 0 to disable external linking mode, 1 to enable it.GIT_ALLOW_PROTOCOLDefined by Git. A colon-separated list of schemes that are allowedto be used with git fetch/clone. If set, any scheme not explicitlymentioned will be considered insecure by 'go get'.Because the variable is defined by Git, the default value cannotbe set using 'go env -w'.

Additional information available from 'go env' but not read from the environment:

GOEXEThe executable file name suffix (".exe" on Windows, "" on other systems).GOGCCFLAGSA space-separated list of arguments supplied to the CC command.GOHOSTARCHThe architecture (GOARCH) of the Go toolchain binaries.GOHOSTOSThe operating system (GOOS) of the Go toolchain binaries.GOMODThe absolute path to the go.mod of the main module.If module-aware mode is enabled, but there is no go.mod, GOMOD will beos.DevNull ("/dev/null" on Unix-like systems, "NUL" on Windows).If module-aware mode is disabled, GOMOD will be the empty string.GOTELEMETRYThe current Go telemetry mode ("off", "local", or "on").See "go help telemetry" for more information.GOTELEMETRYDIRThe directory Go telemetry data is written is written to.GOTOOLDIRThe directory where the go tools (compile, cover, doc, etc...) are installed.GOVERSIONThe version of the installed Go tree, as reported by runtime.Version.

File types

The go command examines the contents of a restricted set of filesin each directory. It identifies which files to examine based onthe extension of the file name. These extensions are:

.goGo source files..c, .hC source files.If the package uses cgo or SWIG, these will be compiled with theOS-native compiler (typically gcc); otherwise they willtrigger an error..cc, .cpp, .cxx, .hh, .hpp, .hxxC++ source files. Only useful with cgo or SWIG, and alwayscompiled with the OS-native compiler..mObjective-C source files. Only useful with cgo, and alwayscompiled with the OS-native compiler..s, .S, .sxAssembler source files.If the package uses cgo or SWIG, these will be assembled with theOS-native assembler (typically gcc (sic)); otherwise theywill be assembled with the Go assembler..swig, .swigcxxSWIG definition files..sysoSystem object files.

Files of each of these types except .syso may contain buildconstraints, but the go command stops scanning for build constraintsat the first item in the file that is not a blank line or //-styleline comment. See the go/build package documentation formore details.

GOAUTH environment variable

GOAUTH is a semicolon-separated list of authentication commands for go-import andHTTPS module mirror interactions. The default is netrc.

The supported authentication commands are:

off

Disables authentication.

netrc

Uses credentials from NETRC or the .netrc file in your home directory.

git dir

Runs 'git credential fill' in dir and uses its credentials. Thego command will run 'git credential approve/reject' to updatethe credential helper's cache.

command

Executes the given command (a space-separated argument list) and attachesthe provided headers to HTTPS requests.The command must produce output in the following format:Response      = { CredentialSet } .CredentialSet = URLLine { URLLine } BlankLine { HeaderLine } BlankLine .URLLine       = /* URL that starts with "https://" */ '\n' .HeaderLine    = /* HTTP Request header */ '\n' .BlankLine     = '\n' .Example:https://example.comhttps://example.net/api/Authorization: Basic <token>https://another-example.org/Example: DataIf the server responds with any 4xx code, the go command will write thefollowing to the program's stdin:Response      = StatusLine { HeaderLine } BlankLine .StatusLine    = Protocol Space Status '\n' .Protocol      = /* HTTP protocol */ .Space         = ' ' .Status        = /* HTTP status code */ .BlankLine     = '\n' .HeaderLine    = /* HTTP Response's header */ '\n' .Example:HTTP/1.1 401 UnauthorizedContent-Length: 19Content-Type: text/plain; charset=utf-8Date: Thu, 07 Nov 2024 18:43:09 GMTNote: it is safe to use net/http.ReadResponse to parse this input.

Before the first HTTPS fetch, the go command will invoke each GOAUTHcommand in the list with no additional arguments and no input.If the server responds with any 4xx code, the go command will invoke theGOAUTH commands again with the URL as an additional command-line argumentand the HTTP Response to the program's stdin.If the server responds with an error again, the fetch fails: a URL-specificGOAUTH will only be attempted once per fetch.

The go.mod file

A module version is defined by a tree of source files, with a go.modfile in its root. When the go command is run, it looks in the currentdirectory and then successive parent directories to find the go.modmarking the root of the main (current) module.

The go.mod file format is described in detail athttps://golang.org/ref/mod#go-mod-file.

To create a new go.mod file, use 'go mod init'. For details see'go help mod init' orhttps://golang.org/ref/mod#go-mod-init.

To add missing module requirements or remove unneeded requirements,use 'go mod tidy'. For details, see 'go help mod tidy' orhttps://golang.org/ref/mod#go-mod-tidy.

To add, upgrade, downgrade, or remove a specific module requirement, use'go get'. For details, see 'go help module-get' orhttps://golang.org/ref/mod#go-get.

To make other changes or to parse go.mod as JSON for use by other tools,use 'go mod edit'. See 'go help mod edit' orhttps://golang.org/ref/mod#go-mod-edit.

GOPATH environment variable

The Go path is used to resolve import statements.It is implemented by and documented in the go/build package.

The GOPATH environment variable lists places to look for Go code.On Unix, the value is a colon-separated string.On Windows, the value is a semicolon-separated string.On Plan 9, the value is a list.

If the environment variable is unset, GOPATH defaultsto a subdirectory named "go" in the user's home directory($HOME/go on Unix, %USERPROFILE%\go on Windows),unless that directory holds a Go distribution.Run "go env GOPATH" to see the current GOPATH.

Seehttps://golang.org/wiki/SettingGOPATH to set a custom GOPATH.

Each directory listed in GOPATH must have a prescribed structure:

The src directory holds source code. The path below srcdetermines the import path or executable name.

The pkg directory holds installed package objects.As in the Go tree, each target operating system andarchitecture pair has its own subdirectory of pkg(pkg/GOOS_GOARCH).

If DIR is a directory listed in the GOPATH, a package withsource in DIR/src/foo/bar can be imported as "foo/bar" andhas its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".

The bin directory holds compiled commands.Each command is named for its source directory, but onlythe final element, not the entire path. That is, thecommand with source in DIR/src/foo/quux is installed intoDIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is strippedso that you can add DIR/bin to your PATH to get at theinstalled commands. If the GOBIN environment variable isset, commands are installed to the directory it names insteadof DIR/bin. GOBIN must be an absolute path.

Here's an example directory layout:

GOPATH=/home/user/go/home/user/go/    src/        foo/            bar/               (go code in package bar)                x.go            quux/              (go code in package main)                y.go    bin/        quux                   (installed command)    pkg/        linux_amd64/            foo/                bar.a          (installed package object)

Go searches each directory listed in GOPATH to find source code,but new packages are always downloaded into the first directoryin the list.

Seehttps://golang.org/doc/code.html for an example.

GOPATH and Modules

When using modules, GOPATH is no longer used for resolving imports.However, it is still used to store downloaded source code (in GOPATH/pkg/mod)and compiled commands (in GOPATH/bin).

Internal Directories

Code in or below a directory named "internal" is importable onlyby code in the directory tree rooted at the parent of "internal".Here's an extended version of the directory layout above:

/home/user/go/    src/        crash/            bang/              (go code in package bang)                b.go        foo/                   (go code in package foo)            f.go            bar/               (go code in package bar)                x.go            internal/                baz/           (go code in package baz)                    z.go            quux/              (go code in package main)                y.go

The code in z.go is imported as "foo/internal/baz", but thatimport statement can only appear in source files in the subtreerooted at foo. The source files foo/f.go, foo/bar/x.go, andfoo/quux/y.go can all import "foo/internal/baz", but the source filecrash/bang/b.go cannot.

Seehttps://golang.org/s/go14internal for details.

Vendor Directories

Go 1.6 includes support for using local copies of external dependenciesto satisfy imports of those dependencies, often referred to as vendoring.

Code below a directory named "vendor" is importable onlyby code in the directory tree rooted at the parent of "vendor",and only using an import path that omits the prefix up to andincluding the vendor element.

Here's the example from the previous section,but with the "internal" directory renamed to "vendor"and a new foo/vendor/crash/bang directory added:

/home/user/go/    src/        crash/            bang/              (go code in package bang)                b.go        foo/                   (go code in package foo)            f.go            bar/               (go code in package bar)                x.go            vendor/                crash/                    bang/      (go code in package bang)                        b.go                baz/           (go code in package baz)                    z.go            quux/              (go code in package main)                y.go

The same visibility rules apply as for internal, but the codein z.go is imported as "baz", not as "foo/vendor/baz".

Code in vendor directories deeper in the source tree shadowscode in higher directories. Within the subtree rooted at foo, an importof "crash/bang" resolves to "foo/vendor/crash/bang", not thetop-level "crash/bang".

Code in vendor directories is not subject to import pathchecking (see 'go help importpath').

When 'go get' checks out or updates a git repository, it now alsoupdates submodules.

Vendor directories do not affect the placement of new repositoriesbeing checked out for the first time by 'go get': those are alwaysplaced in the main GOPATH, never in a vendor subtree.

Seehttps://golang.org/s/go15vendor for details.

Module proxy protocol

A Go module proxy is any web server that can respond to GET requests forURLs of a specified form. The requests have no query parameters, so evena site serving from a fixed file system (including a file:/// URL)can be a module proxy.

For details on the GOPROXY protocol, seehttps://golang.org/ref/mod#goproxy-protocol.

Import path syntax

An import path (see 'go help packages') denotes a package stored in the localfile system. In general, an import path denotes either a standard package (suchas "unicode/utf8") or a package found in one of the work spaces (For moredetails see: 'go help gopath').

Relative import paths

An import path beginning with ./ or ../ is called a relative path.The toolchain supports relative import paths as a shortcut in two ways.

First, a relative path can be used as a shorthand on the command line.If you are working in the directory containing the code imported as"unicode" and want to run the tests for "unicode/utf8", you can type"go test ./utf8" instead of needing to specify the full path.Similarly, in the reverse situation, "go test .." will test "unicode" fromthe "unicode/utf8" directory. Relative patterns are also allowed, like"go test ./..." to test all subdirectories. See 'go help packages' for detailson the pattern syntax.

Second, if you are compiling a Go program not in a work space,you can use a relative path in an import statement in that programto refer to nearby code also not in a work space.This makes it easy to experiment with small multipackage programsoutside of the usual work spaces, but such programs cannot beinstalled with "go install" (there is no work space in which to install them),so they are rebuilt from scratch each time they are built.To avoid ambiguity, Go programs cannot use relative import pathswithin a work space.

Remote import paths

Certain import paths alsodescribe how to obtain the source code for the package usinga revision control system.

A few common code hosting sites have special syntax:

Bitbucket (Git, Mercurial)import "bitbucket.org/user/project"import "bitbucket.org/user/project/sub/directory"GitHub (Git)import "github.com/user/project"import "github.com/user/project/sub/directory"Launchpad (Bazaar)import "launchpad.net/project"import "launchpad.net/project/series"import "launchpad.net/project/series/sub/directory"import "launchpad.net/~user/project/branch"import "launchpad.net/~user/project/branch/sub/directory"IBM DevOps Services (Git)import "hub.jazz.net/git/user/project"import "hub.jazz.net/git/user/project/sub/directory"

For code hosted on other servers, import paths may either be qualifiedwith the version control type, or the go tool can dynamically fetchthe import path over https/http and discover where the code residesfrom a <meta> tag in the HTML.

To declare the code location, an import path of the form

repository.vcs/path

specifies the given repository, with or without the .vcs suffix,using the named version control system, and then the path insidethat repository. The supported version control systems are:

Bazaar      .bzrFossil      .fossilGit         .gitMercurial   .hgSubversion  .svn

For example,

import "example.org/user/foo.hg"

denotes the root directory of the Mercurial repository atexample.org/user/foo, and

import "example.org/repo.git/foo/bar"

denotes the foo/bar directory of the Git repository atexample.org/repo.

When a version control system supports multiple protocols,each is tried in turn when downloading. For example, a Gitdownload tries https://, then git+ssh://.

By default, downloads are restricted to known secure protocols(e.g. https, ssh). To override this setting for Git downloads, theGIT_ALLOW_PROTOCOL environment variable can be set (For more details see:'go help environment').

If the import path is not a known code hosting site and also lacks aversion control qualifier, the go tool attempts to fetch the importover https/http and looks for a <meta> tag in the document's HTML<head>.

The meta tag has the form:

<meta name="go-import" content="import-prefix vcs repo-root">

Starting in Go 1.25, an optional subdirectory will be recognized by thego command:

<meta name="go-import" content="import-prefix vcs repo-root subdir">

The import-prefix is the import path corresponding to the repositoryroot. It must be a prefix or an exact match of the package beingfetched with "go get". If it's not an exact match, another httprequest is made at the prefix to verify the <meta> tags match.

The meta tag should appear as early in the file as possible.In particular, it should appear before any raw JavaScript or CSS,to avoid confusing the go command's restricted parser.

The vcs is one of "bzr", "fossil", "git", "hg", "svn".

The repo-root is the root of the version control systemcontaining a scheme and not containing a .vcs qualifier.

The subdir specifies the directory within the repo-root where theGo module's root (including its go.mod file) is located. It allowsyou to organize your repository with the Go module code in a subdirectoryrather than directly at the repository's root.If set, all vcs tags must be prefixed with "subdir". i.e. "subdir/v1.2.3"

For example,

import "example.org/pkg/foo"

will result in the following requests:

https://example.org/pkg/foo?go-get=1 (preferred)http://example.org/pkg/foo?go-get=1  (fallback, only with use of correctly set GOINSECURE)

If that page contains the meta tag

<meta name="go-import" content="example.org git https://code.org/r/p/exproj">

the go tool will verify thathttps://example.org/?go-get=1 contains thesame meta tag and then download the code from the Git repository athttps://code.org/r/p/exproj

If that page contains the meta tag

<meta name="go-import" content="example.org git https://code.org/r/p/exproj foo/subdir">

the go tool will verify thathttps://example.org/?go-get=1 contains the same metatag and then download the code from the "foo/subdir" subdirectory within the Git repositoryathttps://code.org/r/p/exproj

Downloaded packages are stored in the module cache.Seehttps://golang.org/ref/mod#module-cache.

When using modules, an additional variant of the go-import meta tag isrecognized and is preferred over those listing version control systems.That variant uses "mod" as the vcs in the content value, as in:

<meta name="go-import" content="example.org mod https://code.org/moduleproxy">

This tag means to fetch modules with paths beginning with example.orgfrom the module proxy available at the URLhttps://code.org/moduleproxy.Seehttps://golang.org/ref/mod#goproxy-protocol for details about theproxy protocol.

Import path checking

When the custom import path feature described above redirects to aknown code hosting site, each of the resulting packages has two possibleimport paths, using the custom domain or the known hosting site.

A package statement is said to have an "import comment" if it is immediatelyfollowed (before the next newline) by a comment of one of these two forms:

package math // import "path"package math /* import "path" */

The go command will refuse to install a package with an import commentunless it is being referred to by that import path. In this way, import commentslet package authors make sure the custom import path is used and not adirect path to the underlying code hosting site.

Import path checking is disabled for code found within vendor trees.This makes it possible to copy code into alternate locations in vendor treeswithout needing to update import comments.

Import path checking is also disabled when using modules.Import path comments are obsoleted by the go.mod file's module statement.

Seehttps://golang.org/s/go14customimport for details.

Modules, module versions, and more

Modules are how Go manages dependencies.

A module is a collection of packages that are released, versioned, anddistributed together. Modules may be downloaded directly from version controlrepositories or from module proxy servers.

For a series of tutorials on modules, seehttps://golang.org/doc/tutorial/create-module.

For a detailed reference on modules, seehttps://golang.org/ref/mod.

By default, the go command may download modules fromhttps://proxy.golang.org.It may authenticate modules using the checksum database athttps://sum.golang.org. Both services are operated by the Go team at Google.The privacy policies for these services are available athttps://proxy.golang.org/privacy andhttps://sum.golang.org/privacy,respectively.

The go command's download behavior may be configured using GOPROXY, GOSUMDB,GOPRIVATE, and other environment variables. See 'go help environment'andhttps://golang.org/ref/mod#private-module-privacy for more information.

Module authentication using go.sum

When the go command downloads a module zip file or go.mod file into themodule cache, it computes a cryptographic hash and compares it with a knownvalue to verify the file hasn't changed since it was first downloaded. Knownhashes are stored in a file in the module root directory named go.sum. Hashesmay also be downloaded from the checksum database depending on the values ofGOSUMDB, GOPRIVATE, and GONOSUMDB.

For details, seehttps://golang.org/ref/mod#authenticating.

Package lists and patterns

Many commands apply to a set of packages:

go <action> [packages]

Usually, [packages] is a list of import paths.

An import path that is a rooted path or that begins witha . or .. element is interpreted as a file system path anddenotes the package in that directory.

Otherwise, the import path P denotes the package found inthe directory DIR/src/P for some DIR listed in the GOPATHenvironment variable (For more details see: 'go help gopath').

If no import paths are given, the action applies to thepackage in the current directory.

There are five reserved names for paths that should not be usedfor packages to be built with the go tool:

- "main" denotes the top-level package in a stand-alone executable.

- "all" expands to all packages in the main module (or workspace modules) andtheir dependencies, including dependencies needed by tests of any of those. InGOPATH mode, "all" expands to all packages found in all the GOPATH trees.

- "std" is like all but expands to just the packages in the standardGo library.

- "cmd" expands to the Go repository's commands and theirinternal libraries.

- "tool" expands to the tools defined in the current module's go.mod file.

Package names match against fully-qualified import paths or patterns thatmatch against any number of import paths. For instance, "fmt" refers to thestandard library's package fmt, but "http" alone for package http would notmatch the import path "net/http" from the standard library. Instead, thecomplete import path "net/http" must be used.

Import paths beginning with "cmd/" only match source code inthe Go repository.

An import path is a pattern if it includes one or more "..." wildcards,each of which can match any string, including the empty string andstrings containing slashes. Such a pattern expands to all packagedirectories found in the GOPATH trees with names matching thepatterns.

To make common patterns more convenient, there are two special cases.First, /... at the end of the pattern can match an empty string,so that net/... matches both net and packages in its subdirectories, like net/http.Second, any slash-separated pattern element containing a wildcard neverparticipates in a match of the "vendor" element in the path of a vendoredpackage, so that ./... does not match packages in subdirectories of./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.Note, however, that a directory named vendor that itself contains codeis not a vendored package: cmd/vendor would be a command named vendor,and the pattern cmd/... matches it.See golang.org/s/go15vendor for more about vendoring.

An import path can also name a package to be downloaded froma remote repository. Run 'go help importpath' for details.

Every package in a program must have a unique import path.By convention, this is arranged by starting each path with aunique prefix that belongs to you. For example, paths usedinternally at Google all begin with 'google', and pathsdenoting remote repositories begin with the path to the code,such as 'github.com/user/repo'. Package patterns should include this prefix.For instance, a package called 'http' residing under 'github.com/user/repo',would be addressed with the fully-qualified pattern:'github.com/user/repo/http'.

Packages in a program need not have unique package names,but there are two reserved package names with special meaning.The name main indicates a command, not a library.Commands are built into binaries and cannot be imported.The name documentation indicates documentation fora non-Go program in the directory. Files in package documentationare ignored by the go command.

As a special case, if the package list is a list of .go files from asingle directory, the command is applied to a single synthesizedpackage made up of exactly those files, ignoring any build constraintsin those files and ignoring any other files in the directory.

Directory and file names that begin with "." or "_" are ignoredby the go tool, as are directories named "testdata".

Configuration for downloading non-public code

The go command defaults to downloading modules from the public Go modulemirror at proxy.golang.org. It also defaults to validating downloaded modules,regardless of source, against the public Go checksum database at sum.golang.org.These defaults work well for publicly available source code.

The GOPRIVATE environment variable controls which modules the go commandconsiders to be private (not available publicly) and should therefore not usethe proxy or checksum database. The variable is a comma-separated list ofglob patterns (in the syntax of Go's path.Match) of module path prefixes.For example,

GOPRIVATE=*.corp.example.com,rsc.io/private

causes the go command to treat as private any module with a path prefixmatching either pattern, including git.corp.example.com/xyzzy, rsc.io/private,and rsc.io/private/quux.

For fine-grained control over module download and validation, the GONOPROXYand GONOSUMDB environment variables accept the same kind of glob listand override GOPRIVATE for the specific decision of whether to use the proxyand checksum database, respectively.

For example, if a company ran a module proxy serving private modules,users would configure go using:

GOPRIVATE=*.corp.example.comGOPROXY=proxy.example.comGONOPROXY=none

The GOPRIVATE variable is also used to define the "public" and "private"patterns for the GOVCS variable; see 'go help vcs'. For that usage,GOPRIVATE applies even in GOPATH mode. In that case, it matches import pathsinstead of module paths.

The 'go env -w' command (see 'go help env') can be used to set these variablesfor future go command invocations.

For more details, seehttps://golang.org/ref/mod#private-modules.

Testing flags

The 'go test' command takes both flags that apply to 'go test' itselfand flags that apply to the resulting test binary.

Several of the flags control profiling and write an execution profilesuitable for "go tool pprof"; run "go tool pprof -h" for moreinformation. The --alloc_space, --alloc_objects, and --show_bytesoptions of pprof control how the information is presented.

The following flags are recognized by the 'go test' command andcontrol the execution of any test:

-bench regexp    Run only those benchmarks matching a regular expression.    By default, no benchmarks are run.    To run all benchmarks, use '-bench .' or '-bench=.'.    The regular expression is split by unbracketed slash (/)    characters into a sequence of regular expressions, and each    part of a benchmark's identifier must match the corresponding    element in the sequence, if any. Possible parents of matches    are run with b.N=1 to identify sub-benchmarks. For example,    given -bench=X/Y, top-level benchmarks matching X are run    with b.N=1 to find any sub-benchmarks matching Y, which are    then run in full.-benchtime t    Run enough iterations of each benchmark to take t, specified    as a time.Duration (for example, -benchtime 1h30s).    The default is 1 second (1s).    The special syntax Nx means to run the benchmark N times    (for example, -benchtime 100x).-count n    Run each test, benchmark, and fuzz seed n times (default 1).    If -cpu is set, run n times for each GOMAXPROCS value.    Examples are always run once. -count does not apply to    fuzz tests matched by -fuzz.-cover    Enable coverage analysis.    Note that because coverage works by annotating the source    code before compilation, compilation and test failures with    coverage enabled may report line numbers that don't correspond    to the original sources.-covermode set,count,atomic    Set the mode for coverage analysis for the package[s]    being tested. The default is "set" unless -race is enabled,    in which case it is "atomic".    The values:set: bool: does this statement run?count: int: how many times does this statement run?atomic: int: count, but correct in multithreaded tests;significantly more expensive.    Sets -cover.-coverpkg pattern1,pattern2,pattern3    Apply coverage analysis in each test to packages whose import paths    match the patterns. The default is for each test to analyze only    the package being tested. See 'go help packages' for a description    of package patterns. Sets -cover.-cpu 1,2,4    Specify a list of GOMAXPROCS values for which the tests, benchmarks or    fuzz tests should be executed. The default is the current value    of GOMAXPROCS. -cpu does not apply to fuzz tests matched by -fuzz.-failfast    Do not start new tests after the first test failure.-fullpath    Show full file names in the error messages.-fuzz regexp    Run the fuzz test matching the regular expression. When specified,    the command line argument must match exactly one package within the    main module, and regexp must match exactly one fuzz test within    that package. Fuzzing will occur after tests, benchmarks, seed corpora    of other fuzz tests, and examples have completed. See the Fuzzing    section of the testing package documentation for details.-fuzztime t    Run enough iterations of the fuzz target during fuzzing to take t,    specified as a time.Duration (for example, -fuzztime 1h30s).The default is to run forever.    The special syntax Nx means to run the fuzz target N times    (for example, -fuzztime 1000x).-fuzzminimizetime t    Run enough iterations of the fuzz target during each minimization    attempt to take t, as specified as a time.Duration (for example,    -fuzzminimizetime 30s).The default is 60s.    The special syntax Nx means to run the fuzz target N times    (for example, -fuzzminimizetime 100x).-json    Log verbose output and test results in JSON. This presents the    same information as the -v flag in a machine-readable format.-list regexp    List tests, benchmarks, fuzz tests, or examples matching the regular    expression. No tests, benchmarks, fuzz tests, or examples will be run.    This will only list top-level tests. No subtest or subbenchmarks will be    shown.-parallel n    Allow parallel execution of test functions that call t.Parallel, and    fuzz targets that call t.Parallel when running the seed corpus.    The value of this flag is the maximum number of tests to run    simultaneously.    While fuzzing, the value of this flag is the maximum number of    subprocesses that may call the fuzz function simultaneously, regardless of    whether T.Parallel is called.    By default, -parallel is set to the value of GOMAXPROCS.    Setting -parallel to values higher than GOMAXPROCS may cause degraded    performance due to CPU contention, especially when fuzzing.    Note that -parallel only applies within a single test binary.    The 'go test' command may run tests for different packages    in parallel as well, according to the setting of the -p flag    (see 'go help build').-run regexp    Run only those tests, examples, and fuzz tests matching the regular    expression. For tests, the regular expression is split by unbracketed    slash (/) characters into a sequence of regular expressions, and each    part of a test's identifier must match the corresponding element in    the sequence, if any. Note that possible parents of matches are    run too, so that -run=X/Y matches and runs and reports the result    of all tests matching X, even those without sub-tests matching Y,    because it must run them to look for those sub-tests.    See also -skip.-short    Tell long-running tests to shorten their run time.    It is off by default but set during all.bash so that installing    the Go tree can run a sanity check but not spend time running    exhaustive tests.-shuffle off,on,N    Randomize the execution order of tests and benchmarks.    It is off by default. If -shuffle is set to on, then it will seed    the randomizer using the system clock. If -shuffle is set to an    integer N, then N will be used as the seed value. In both cases,    the seed will be reported for reproducibility.-skip regexp    Run only those tests, examples, fuzz tests, and benchmarks that    do not match the regular expression. Like for -run and -bench,    for tests and benchmarks, the regular expression is split by unbracketed    slash (/) characters into a sequence of regular expressions, and each    part of a test's identifier must match the corresponding element in    the sequence, if any.-timeout d    If a test binary runs longer than duration d, panic.    If d is 0, the timeout is disabled.    The default is 10 minutes (10m).-v    Verbose output: log all tests as they are run. Also print all    text from Log and Logf calls even if the test succeeds.-vet list    Configure the invocation of "go vet" during "go test"    to use the comma-separated list of vet checks.    If list is empty, "go test" runs "go vet" with a curated list of    checks believed to be always worth addressing.    If list is "off", "go test" does not run "go vet" at all.

The following flags are also recognized by 'go test' and can be used toprofile the tests during execution:

-benchmem    Print memory allocation statistics for benchmarks.    Allocations made in C or using C.malloc are not counted.-blockprofile block.out    Write a goroutine blocking profile to the specified file    when all tests are complete.    Writes test binary as -c would.-blockprofilerate n    Control the detail provided in goroutine blocking profiles by    calling runtime.SetBlockProfileRate with n.    See 'go doc runtime.SetBlockProfileRate'.    The profiler aims to sample, on average, one blocking event every    n nanoseconds the program spends blocked. By default,    if -test.blockprofile is set without this flag, all blocking events    are recorded, equivalent to -test.blockprofilerate=1.-coverprofile cover.out    Write a coverage profile to the file after all tests have passed.    Sets -cover.-cpuprofile cpu.out    Write a CPU profile to the specified file before exiting.    Writes test binary as -c would.-memprofile mem.out    Write an allocation profile to the file after all tests have passed.    Writes test binary as -c would.-memprofilerate n    Enable more precise (and expensive) memory allocation profiles by    setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.    To profile all memory allocations, use -test.memprofilerate=1.-mutexprofile mutex.out    Write a mutex contention profile to the specified file    when all tests are complete.    Writes test binary as -c would.-mutexprofilefraction n    Sample 1 in n stack traces of goroutines holding a    contended mutex.-outputdir directory    Place output files from profiling in the specified directory,    by default the directory in which "go test" is running.-trace trace.out    Write an execution trace to the specified file before exiting.

Each of these flags is also recognized with an optional 'test.' prefix,as in -test.v. When invoking the generated test binary (the result of'go test -c') directly, however, the prefix is mandatory.

The 'go test' command rewrites or removes recognized flags,as appropriate, both before and after the optional package list,before invoking the test binary.

For instance, the command

go test -v -myflag testdata -cpuprofile=prof.out -x

will compile the test binary and then run it as

pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out

(The -x flag is removed because it applies only to the go command'sexecution, not to the test itself.)

The test flags that generate profiles (other than for coverage) alsoleave the test binary in pkg.test for use when analyzing the profiles.

When 'go test' runs a test binary, it does so from within thecorresponding package's source code directory. Depending on the test,it may be necessary to do the same when invoking a generated testbinary directly. Because that directory may be located within themodule cache, which may be read-only and is verified by checksums, thetest must not write to it or any other directory within the moduleunless explicitly requested by the user (such as with the -fuzz flag,which writes failures to testdata/fuzz).

The command-line package list, if present, must appear before anyflag not known to the go test command. Continuing the example above,the package list would have to appear before -myflag, but could appearon either side of -v.

When 'go test' runs in package list mode, 'go test' caches successfulpackage test results to avoid unnecessary repeated running of tests. Todisable test caching, use any test flag or argument other than thecacheable flags. The idiomatic way to disable test caching explicitlyis to use -count=1.

To keep an argument for a test binary from being interpreted as aknown flag or a package name, use -args (see 'go help test') whichpasses the remainder of the command line through to the test binaryuninterpreted and unaltered.

For instance, the command

go test -v -args -x -v

will compile the test binary and then run it as

pkg.test -test.v -x -v

Similarly,

go test -args math

will compile the test binary and then run it as

pkg.test math

In the first example, the -x and the second -v are passed through to thetest binary unchanged and with no effect on the go command itself.In the second example, the argument math is passed through to the testbinary, instead of being interpreted as the package list.

Testing functions

The 'go test' command expects to find test, benchmark, and example functionsin the "*_test.go" files corresponding to the package under test.

A test function is one named TestXxx (where Xxx does not start with alower case letter) and should have the signature,

func TestXxx(t *testing.T) { ... }

A benchmark function is one named BenchmarkXxx and should have the signature,

func BenchmarkXxx(b *testing.B) { ... }

A fuzz test is one named FuzzXxx and should have the signature,

func FuzzXxx(f *testing.F) { ... }

An example function is similar to a test function but, instead of using*testing.T to report success or failure, prints output to os.Stdout.If the last comment in the function starts with "Output:" then the outputis compared exactly against the comment (see examples below). If the lastcomment begins with "Unordered output:" then the output is compared to thecomment, however the order of the lines is ignored. An example with no suchcomment is compiled but not executed. An example with no text after"Output:" is compiled, executed, and expected to produce no output.

Godoc displays the body of ExampleXxx to demonstrate the useof the function, constant, or variable Xxx. An example of a method M withreceiver type T or *T is named ExampleT_M. There may be multiple examplesfor a given function, constant, or variable, distinguished by a trailing _xxx,where xxx is a suffix not beginning with an upper case letter.

Here is an example of an example:

func ExamplePrintln() {Println("The output of\nthis example.")// Output: The output of// this example.}

Here is another example where the ordering of the output is ignored:

func ExamplePerm() {for _, value := range Perm(4) {fmt.Println(value)}// Unordered output: 4// 2// 1// 3// 0}

The entire test file is presented as the example when it contains a singleexample function, at least one other function, type, variable, or constantdeclaration, and no tests, benchmarks, or fuzz tests.

See the documentation of the testing package for more information.

Controlling version control with GOVCS

The 'go get' command can run version control commands like gitto download imported code. This functionality is critical to the decentralizedGo package ecosystem, in which code can be imported from any server,but it is also a potential security problem, if a malicious server finds away to cause the invoked version control command to run unintended code.

To balance the functionality and security concerns, the 'go get' commandby default will only use git and hg to download code from public servers.But it will use any known version control system (bzr, fossil, git, hg, svn)to download code from private servers, defined as those hosting packagesmatching the GOPRIVATE variable (see 'go help private'). The rationale behindallowing only Git and Mercurial is that these two systems have had the mostattention to issues of being run as clients of untrusted servers. In contrast,Bazaar, Fossil, and Subversion have primarily been used in trusted,authenticated environments and are not as well scrutinized as attack surfaces.

The version control command restrictions only apply when using direct versioncontrol access to download code. When downloading modules from a proxy,'go get' uses the proxy protocol instead, which is always permitted.By default, the 'go get' command uses the Go module mirror (proxy.golang.org)for public packages and only falls back to version control for privatepackages or when the mirror refuses to serve a public package (typically forlegal reasons). Therefore, clients can still access public code served fromBazaar, Fossil, or Subversion repositories by default, because those downloadsuse the Go module mirror, which takes on the security risk of running theversion control commands using a custom sandbox.

The GOVCS variable can be used to change the allowed version control systemsfor specific packages (identified by a module or import path).The GOVCS variable applies when building package in both module-aware modeand GOPATH mode. When using modules, the patterns match against the module path.When using GOPATH, the patterns match against the import path corresponding tothe root of the version control repository.

The general form of the GOVCS setting is a comma-separated list ofpattern:vcslist rules. The pattern is a glob pattern that must matchone or more leading elements of the module or import path. The vcslistis a pipe-separated list of allowed version control commands, or "all"to allow use of any known command, or "off" to disallow all commands.Note that if a module matches a pattern with vcslist "off", it may still bedownloaded if the origin server uses the "mod" scheme, which instructs thego command to download the module using the GOPROXY protocol.The earliest matching pattern in the list applies, even if later patternsmight also match.

For example, consider:

GOVCS=github.com:git,evil.com:off,*:git|hg

With this setting, code with a module or import path beginning withgithub.com/ can only use git; paths on evil.com cannot use any versioncontrol command, and all other paths (* matches everything) can useonly git or hg.

The special patterns "public" and "private" match public and privatemodule or import paths. A path is private if it matches the GOPRIVATEvariable; otherwise it is public.

If no rules in the GOVCS variable match a particular module or import path,the 'go get' command applies its default rule, which can now be summarizedin GOVCS notation as 'public:git|hg,private:all'.

To allow unfettered use of any version control system for any package, use:

GOVCS=*:all

To disable all use of version control, use:

GOVCS=*:off

The 'go env -w' command (see 'go help env') can be used to set the GOVCSvariable for future go command invocations.

Source Files

View all Source files

Directories

PathSynopsis
internal
auth
Package auth provides access to user-provided authentication credentials.
Package auth provides access to user-provided authentication credentials.
base
Package base defines shared basic pieces of the go command, in particular logging and the Command structure.
Package base defines shared basic pieces of the go command, in particular logging and the Command structure.
bug
Package bug implements the “go bug” command.
Package bug implements the “go bug” command.
cache
Package cache implements a build artifact cache.
Package cache implements a build artifact cache.
cacheprog
Package cacheprog defines the protocol for a GOCACHEPROG program.
Package cacheprog defines the protocol for a GOCACHEPROG program.
cfg
Package cfg holds configuration shared by multiple parts of the go command.
Package cfg holds configuration shared by multiple parts of the go command.
clean
Package clean implements the “go clean” command.
Package clean implements the “go clean” command.
cmdflag
Package cmdflag handles flag processing common to several go tools.
Package cmdflag handles flag processing common to several go tools.
doc
Package doc implements the “go doc” command.
Package doc implements the “go doc” command.
envcmd
Package envcmd implements the “go env” command.
Package envcmd implements the “go env” command.
fips140
Package fips implements support for the GOFIPS140 build setting.
Package fips implements support for the GOFIPS140 build setting.
fix
Package fix implements the “go fix” command.
Package fix implements the “go fix” command.
fmtcmd
Package fmtcmd implements the “go fmt” command.
Package fmtcmd implements the “go fmt” command.
fsys
Package fsys implements a virtual file system that the go command uses to read source file trees.
Package fsys implements a virtual file system that the go command uses to read source file trees.
generate
Package generate implements the “go generate” command.
Package generate implements the “go generate” command.
gover
Package gover implements support for Go toolchain versions like 1.21.0 and 1.21rc1.
Package gover implements support for Go toolchain versions like 1.21.0 and 1.21rc1.
help
Package help implements the “go help” command.
Package help implements the “go help” command.
list
Package list implements the “go list” command.
Package list implements the “go list” command.
load
Package load loads packages.
Package load loads packages.
lockedfile
Package lockedfile creates and manipulates files whose contents should only change atomically.
Package lockedfile creates and manipulates files whose contents should only change atomically.
lockedfile/internal/filelock
Package filelock provides a platform-independent API for advisory file locking.
Package filelock provides a platform-independent API for advisory file locking.
mmap
The mmap package provides an abstraction for memory mapping files on different platforms.
The mmap package provides an abstraction for memory mapping files on different platforms.
modcmd
Package modcmd implements the “go mod” command.
Package modcmd implements the “go mod” command.
modfetch/codehost
Package codehost defines the interface implemented by a code hosting source, along with support code for use by implementations.
Package codehost defines the interface implemented by a code hosting source, along with support code for use by implementations.
modget
Package modget implements the module-aware “go get” command.
Package modget implements the module-aware “go get” command.
mvs
Package mvs implements Minimal Version Selection.
Package mvs implements Minimal Version Selection.
run
Package run implements the “go run” command.
Package run implements the “go run” command.
str
Package str provides string manipulation utilities.
Package str provides string manipulation utilities.
telemetrycmd
Package telemetrycmd implements the "go telemetry" command.
Package telemetrycmd implements the "go telemetry" command.
tool
Package tool implements the “go tool” command.
Package tool implements the “go tool” command.
toolchain
Package toolchain implements dynamic switching of Go toolchains.
Package toolchain implements dynamic switching of Go toolchains.
vcweb
Package vcweb serves version control repos for testing the go command.
Package vcweb serves version control repos for testing the go command.
vcweb/vcstest
Package vcstest serves the repository scripts in cmd/go/testdata/vcstest using the vcweb script engine.
Package vcstest serves the repository scripts in cmd/go/testdata/vcstest using the vcweb script engine.
version
Package version implements the “go version” command.
Package version implements the “go version” command.
vet
Package vet implements the “go vet” command.
Package vet implements the “go vet” command.
web
Package web defines minimal helper routines for accessing HTTP/HTTPS resources without requiring external dependencies on the net package.
Package web defines minimal helper routines for accessing HTTP/HTTPS resources without requiring external dependencies on the net package.
workcmd
Package workcmd implements the “go work” command.
Package workcmd implements the “go work” command.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp