go

Overview

Go is a tool for managing Go source code.

​ Go 是一个用于管理 Go 源代码的工具。

Usage:

go <command> [arguments]

The commands are:

​ 可用的命令有:

bug         开始一个错误报告  start a bug report
build       编译包及其依赖项 compile packages and dependencies
clean       移除目标文件和缓存文件 remove object files and cached files
doc         显示包或符号的文档 show documentation for package or symbol
env         打印 Go 环境信息 print Go environment information
fix         更新包以使用新的 API update packages to use new APIs
fmt         使用 gofmt 重新格式化包源代码 gofmt (reformat) package sources
generate    通过处理源代码生成 Go 文件 generate Go files by processing source
get         添加依赖项到当前模块并安装它们 add dependencies to current module and install them
install     编译并安装包及其依赖项 compile and install packages and dependencies
list        列出包或模块 list packages or modules
mod         模块维护 module maintenance
work        工作区维护 workspace maintenance
run         编译并运行 Go 程序 compile and run Go program
telemetry   管理遥测数据和设置 manage telemetry data and settings
test        测试包 test packages
tool        运行指定的 go 工具 run specified go tool
version     打印 Go 版本 print Go version
vet         报告包中可能的错误 report likely mistakes in packages

Use “go help ” for more information about a command.

​ 使用 “go help <命令>” 获取更多关于某个命令的信息。

Additional help topics:

​ 其他帮助主题:

buildconstraint 构建约束 build constraints
buildmode       构建模式 build modes
c               Go 与 C 之间的调用 calling between Go and C
cache           构建和测试缓存 build and test caching
environment     环境变量 environment variables
filetype        文件类型 file types
go.mod          go.mod 文件 the go.mod file
gopath          GOPATH 环境变量 GOPATH environment variable
goproxy         模块代理协议 module proxy protocol
importpath      导入路径语法 import path syntax
modules         模块、模块版本等 modules, module versions, and more
module-auth     使用 go.sum 进行模块认证 module authentication using go.sum
packages        包列表和模式 package lists and patterns
private         下载非公共代码的配置 configuration for downloading non-public code
testflag        测试标志 testing flags
testfunc        测试函数 testing functions
vcs             使用 GOVCS 控制版本管理 controlling version control with GOVCS

Use “go help ” for more information about that topic.

​ 使用 “go help <主题>” 获取更多关于该主题的信息。

启动错误报告 Start a bug report

Usage:

go bug

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

​ Bug 会打开默认浏览器并开始一个新的错误报告。该报告包含有用的系统信息。

编译包及其依赖项 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.

​ Build 编译由导入路径指定的包及其依赖项,但不会安装编译结果。

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.

​ 如果 build 的参数是来自单个目录的一组 .go 文件,build 会将它们视为指定单个包的源文件列表。

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

​ 在编译包时,build 会忽略以 ‘_test.go’ 结尾的文件。

When compiling a single main package, build writes the resulting executable to an output file named after the last non-major-version component of the package import path. The ‘.exe’ suffix is added when 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’.

​ 当编译单个主包时,build 会将生成的可执行文件写入一个以包导入路径中最后一个非主版本组件命名的输出文件。写入 Windows 可执行文件时会添加 ‘.exe’ 后缀。例如,‘go build example/sam’ 会生成 ‘sam’ 或 ‘sam.exe’。‘go build example.com/foo/v2’ 会生成 ‘foo’ 或 ‘foo.exe’,而不是 ‘v2.exe’。

When compiling a package from a list of .go files, the executable is named after the first source file. ‘go build ed.go rx.go’ writes ’ed’ or ’ed.exe’.

​ 当从一组 .go 文件编译一个包时,生成的可执行文件会以第一个源文件命名。例如,‘go build ed.go rx.go’ 会生成 ’ed’ 或 ’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.

​ 当编译多个包或单个非主包时,build 会编译这些包,但丢弃生成的对象文件,仅用于检查这些包是否可以成功编译。

The -o flag forces build to write the resulting executable or object to the named output file or directory, instead of the default behavior described in the last two paragraphs. If the named output is an existing directory or ends with a slash or backslash, then any resulting executables will be written to that directory.

​ -o 标志会强制 build 将生成的可执行文件或对象文件写入指定的输出文件或目录,而不是默认行为。如果指定的输出是一个已存在的目录或以斜杠或反斜杠结尾,则任何生成的可执行文件将写入该目录。

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

​ 构建标志由 buildcleangetinstalllistruntest 命令共享:

-C dir
	Change to dir before running the command.
	Any files named on the command line are interpreted after
	changing directories.
	If used, this flag must be the first one in the command line.
	在运行命令之前切换到目录 dir。
	命令行中指定的文件在切换目录之后进行解释。
	如果使用该标志,它必须是命令行中的第一个。
-a
	force rebuilding of packages that are already up-to-date.
	强制重新构建已经是最新的包。
-n
	print the commands but do not run them.
	打印命令但不执行它们。
-p n
	the number of programs, such as build commands or
	test binaries, that can be run in parallel.
	The default is GOMAXPROCS, normally the number of CPUs available.
	可以并行运行的程序数量,例如构建命令或测试二进制文件。
	默认值是 GOMAXPROCS,通常为可用的 CPU 数量。
	
-race
	enable 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).
	启用数据竞争检测。
	仅在以下平台支持:linux/amd64、freebsd/amd64、darwin/amd64、darwin/arm64、windows/amd64、
	linux/ppc64le 和 linux/arm64(仅适用于 48 位 VMA)。
	
-msan
	enable interoperation with memory sanitizer.
	Supported only on linux/amd64, linux/arm64, linux/loong64, freebsd/amd64
	and only with Clang/LLVM as the host C compiler.
	PIE build mode will be used on all platforms except linux/amd64.
	启用与内存消毒器的协作。
	仅在以下平台支持:linux/amd64、linux/arm64、linux/loong64、freebsd/amd64,
	并且仅在主机 C 编译器为 Clang/LLVM 时支持。
	除 linux/amd64 外,所有平台都将使用 PIE 构建模式。
	
-asan
	enable 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 higher
	or Clang/LLVM 9 and higher.
	And supported on linux/loong64 only with Clang/LLVM 16 and higher.
	启用与地址消毒器的协作。
	仅在以下平台支持:linux/arm64、linux/amd64、linux/loong64。
	在 linux/amd64 或 linux/arm64 平台上支持,并且仅支持 GCC 7 及以上版本
	或 Clang/LLVM 9 及以上版本。
	在 linux/loong64 平台上仅支持 Clang/LLVM 16 及以上版本。
	
-cover
	enable code coverage instrumentation.
	启用代码覆盖率检测。
	
-covermode set,count,atomic
	set 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.
	设置覆盖率分析模式。
	默认模式为 "set",除非启用了 -race,在这种情况下默认为 "atomic"。
	值包括:
	set: bool: 该语句是否运行?
	count: int: 该语句运行了多少次?
	atomic: int: 计数,但在多线程测试中是正确的;
		显著更昂贵。
	设置 -cover。
	
-coverpkg pattern1,pattern2,pattern3
	For a build that targets package 'main' (e.g. building a Go
	executable), apply coverage analysis to each package matching
	the patterns. The default is to apply coverage analysis to
	packages in the main Go module. See 'go help packages' for a
	description of package patterns.  Sets -cover.
	对于目标为包 'main'(例如构建 Go 可执行文件)的构建,应用覆盖率分析
	到与模式匹配的每个包。默认情况下,覆盖率分析应用于主 Go 模块中的包。
	参见 'go help packages' 了解包模式的描述。设置 -cover。
	
-v
	print the names of packages as they are compiled.
	在编译时打印包的名称。
	
-work
	print the name of the temporary work directory and
	do not delete it when exiting.
	打印临时工作目录的名称,并在退出时不删除它。
	
-x
	print the commands.
	打印命令。
	
-asmflags '[pattern=]arg list'
	arguments to pass on each go tool asm invocation.
	传递给每个 go 工具 asm 调用的参数。
	
-buildmode mode
	build mode to use. See 'go help buildmode' for more.
	使用的构建模式。参见 'go help buildmode' 了解更多信息。
	
-buildvcs
	Whether to stamp binaries with version control information
	("true", "false", or "auto"). By default ("auto"), version control
	information is stamped into a binary if the main package, the main module
	containing 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 but
	cannot be included due to a missing tool or ambiguous directory structure.
	是否在二进制文件中加入版本控制信息
	("true"、"false" 或 "auto")。默认情况下 ("auto"),如果主包、包含它的主模块
	和当前目录都在同一个仓库中,版本控制信息会被加入到二进制文件中。
	使用 -buildvcs=false 总是省略版本控制信息,或者
	使用 -buildvcs=true 当版本控制信息可用但由于缺少工具或目录结构不明确
	无法包含时会报错。
	
-compiler name
	name of compiler to use, as in runtime.Compiler (gccgo or gc).
	要使用的编译器名称,如 runtime.Compiler 所示(gccgo 或 gc)。
	
-gccgoflags '[pattern=]arg list'
	arguments to pass on each gccgo compiler/linker invocation.
	传递给每个 gccgo 编译器/链接器调用的参数。
	
-gcflags '[pattern=]arg list'
	arguments to pass on each go tool compile invocation.
	传递给每个 go 工具编译调用的参数。
	
-installsuffix suffix
	a 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 race
	or, if set explicitly, has _race appended to it. Likewise for the -msan
	and -asan flags. Using a -buildmode option that requires non-default compile
	flags has a similar effect.
	用于包安装目录名称的后缀,以便将输出与默认构建区分开。
	如果使用了 -race 标志,安装后缀会自动设置为 race,或者如果明确设置,
	会在其后追加 _race。同样适用于 -msan 和 -asan 标志。使用需要非默认编译标志的
	-buildmode 选项也会产生类似的效果。
	
-ldflags '[pattern=]arg list'
	arguments to pass on each go tool link invocation.
	传递给每个 go 工具链接调用的参数。
	
-linkshared
	build code that will be linked against shared libraries previously
	created with -buildmode=shared.
	构建将链接到以前使用 -buildmode=shared 创建的共享库的代码。
	
-mod mode
	module download mode to use: readonly, vendor, or mod.
	By default, if a vendor directory is present and the go version in go.mod
	is 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.
	要使用的模块下载模式:readonly、vendor 或 mod。
	默认情况下,如果存在 vendor 目录并且 go.mod 中的 go 版本是 1.14 或更高版本,
	go 命令的行为就像设置了 -mod=vendor。
	否则,go 命令的行为就像设置了 -mod=readonly。
	详情参见 https://golang.org/ref/mod#build-commands。
	
-modcacherw
	leave newly-created directories in the module cache read-write
	instead of making them read-only.
	使新创建的模块缓存目录保持读写状态,而不是将其设为只读。
	
-modfile file
	in module aware mode, read (and possibly write) an alternate go.mod
	file instead of the one in the module root directory. A file named
	"go.mod" must still be present in order to determine the module root
	directory, but it is not accessed. When -modfile is specified, an
	alternate go.sum file is also used: its path is derived from the
	-modfile flag by trimming the ".mod" extension and appending ".sum".
	在模块感知模式下,读取(并可能写入)一个替代的 go.mod 文件,
	而不是模块根目录中的文件。必须仍然存在一个名为 "go.mod" 的文件,以便确定模块根目录,
	但它不会被访问。当指定了 -modfile 时,也会使用一个替代的 go.sum 文件:
	其路径是通过从 -modfile 标志中去掉 ".mod" 扩展名并追加 ".sum" 得到的。
	
-overlay file
	read a JSON config file that provides an overlay for build operations.
	The file is a JSON struct with a single field, named 'Replace', that
	maps each disk file path (a string) to its backing file path, so that
	a build will run as if the disk file path exists with the contents
	given by the backing file paths, or as if the disk file path does not
	exist if its backing file path is empty. Support for the -overlay flag
	has some limitations: importantly, cgo files included from outside the
	include path must be in the same directory as the Go package they are
	included from, and overlays will not appear when binaries and tests are
	run through go run and go test respectively.
	读取一个 JSON 配置文件,该文件为构建操作提供了一个覆盖层。
	该文件是一个具有单个字段 'Replace' 的 JSON 结构体,该字段将每个磁盘文件路径
	(字符串)映射到其后备文件路径,这样构建操作将运行得好像磁盘文件路径存在,
	其内容由后备文件路径提供,或者如果后备文件路径为空,则好像磁盘文件路径不存在一样。
	对 -overlay 标志的支持有一些限制:重要的是,来自包含路径之外的 cgo 文件
	必须与包含它们的 Go 包在同一目录中,并且覆盖层不会在通过 go run 和 go test
	分别运行二进制文件和测试时出现。
	
-pgo file
	specify the file path of a profile for profile-guided optimization (PGO).
	When the special name "auto" is specified, for each main package in the
	build, the go command selects a file named "default.pgo" in the package's
	directory 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".
	指定用于配置文件引导优化 (PGO) 的配置文件路径。
	当指定特殊名称 "auto" 时,对于构建中的每个主包,go 命令会在包目录中选择名为
	"default.pgo" 的文件(如果该文件存在),并将其应用于主包的(传递的)依赖项
	(其他包不会受到影响)。特殊名称 "off" 会关闭 PGO。默认值为 "auto"。
	
-pkgdir dir
	install 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.
	从 dir 安装并加载所有包,而不是使用通常的位置。
	例如,当使用非标准配置进行构建时,使用 -pkgdir 将生成的包保存在单独的位置。
	
-tags tag,list
	a comma-separated list of additional build tags to consider satisfied
	during the build. For more information about build tags, see
	'go help buildconstraint'. (Earlier versions of Go used a
	space-separated list, and that form is deprecated but still recognized.)
	在构建期间要考虑满足的一组额外构建标签(用逗号分隔的列表)。
	关于构建标签的更多信息,参见 'go help buildconstraint'。
	(早期版本的 Go 使用了空格分隔的列表,这种形式已经被弃用但仍然被识别。)
	
-trimpath
	remove all file system paths from the resulting executable.
	Instead of absolute file system paths, the recorded file names
	will begin either a module path@version (when using modules),
	or a plain import path (when using the standard library, or GOPATH).
	从生成的可执行文件中移除所有文件系统路径。
	而不是绝对的文件系统路径,记录的文件名将从模块路径@版本(使用模块时)
	或简单的导入路径(使用标准库或 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.
	用于调用工具链程序(如 vet 和 asm)的程序。
	例如,go 命令将运行 'cmd args /path/to/asm <asm 的参数>',而不是运行 asm。
	TOOLEXEC_IMPORTPATH 环境变量将被设置,与 'go list -f {{.ImportPath}}' 对应于被构建的包。

The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a space-separated list of arguments to pass to an underlying tool during the build. To embed spaces in an element in the list, surround it with either single or double quotes. The argument list may be preceded by a package pattern and an equal sign, which restricts the use of that argument list to the building of packages matching that pattern (see ‘go help packages’ for a description of package patterns). Without a pattern, the argument list applies only to the packages named on the command line. The flags may be repeated with different patterns in order to specify different arguments for different sets of packages. If a package matches patterns given in multiple flags, the latest match on the command line wins. For example, ‘go build -gcflags=-S fmt’ prints the disassembly only for package fmt, while ‘go build -gcflags=all=-S fmt’ prints the disassembly for fmt and all its dependencies.

-asmflags-gccgoflags-gcflags-ldflags 标志接受一个空格分隔的参数列表,传递给构建期间的底层工具。要在列表中的元素中嵌入空格,可以使用单引号或双引号将其括起来。参数列表可以由包模式和等号前缀,这限制了参数列表仅用于构建与该模式匹配的包(参见 ‘go help packages’ 了解包模式的描述)。如果没有模式,参数列表仅适用于命令行上指定的包。可以使用不同的模式重复这些标志,以便为不同的包集指定不同的参数。如果一个包与多个标志中的模式匹配,则命令行上最新的匹配优先。例如,go build -gcflags=-S fmt 仅打印包 fmt 的反汇编信息,而 go build -gcflags=all=-S fmt 会打印 fmt 及其所有依赖项的反汇编信息。

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’.

​ 有关如何指定包的更多信息,请参阅 ‘go help packages’。有关包和二进制文件安装位置的更多信息,请运行 ‘go help gopath’。有关 Go 与 C/C++ 之间调用的更多信息,请参阅 ‘go help c’。

Note: Build adheres to certain conventions such as those described by ‘go help gopath’. Not all projects can follow these conventions, however. Installations that have their own conventions or that use a separate software build system may choose to use lower-level invocations such as ‘go tool compile’ and ‘go tool link’ to avoid some of the overheads and design decisions of the build tool.

​ 注意:构建遵循某些约定,例如 ‘go help gopath’ 中描述的那些。然而,并非所有项目都能遵循这些约定。使用自定义约定或单独的软件构建系统的安装可能会选择使用较低级的调用,例如 ‘go tool compile’ 和 ‘go tool link’,以避免构建工具的一些开销和设计决策。

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

​ 另请参阅: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 other tools or by manual invocations of go build.

​ clean 会从包的源文件目录中删除目标文件。go 命令会将大多数目标文件构建到一个临时目录中,因此 go clean 主要关注其他工具或手动调用 go build 留下的目标文件。

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

​ 如果指定了包参数或设置了 -i-r 标志,clean 会从与导入路径相对应的源目录中删除以下文件:

_obj/            旧的对象文件目录,遗留自 Makefile - old object directory, left from Makefiles
_test/           旧的测试目录,遗留自 Makefile - old test directory, left from Makefiles
_testmain.go     旧的 gotest 文件,遗留自 Makefile - old gotest file, left from Makefiles
test.out         旧的测试日志,遗留自 Makefile - old test log, left from Makefiles
build.out        旧的构建日志,遗留自 Makefile - old test log, left from Makefiles
*.[568ao]        对象文件,遗留自 Makefile - object files, left from Makefiles

DIR(.exe)        来自 `go build` from go build
DIR.test(.exe)   来自 `go test -c` from go test -c
MAINFILE(.exe)   来自 `go build MAINFILE.go` from go build MAINFILE.go
*.so             来自 SWIG from SWIG

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

​ 在列表中,DIR 代表目录的最后路径元素,MAINFILE 是目录中任意 Go 源文件的基本名称,且这些文件在构建包时不包括在内。

The -i flag causes clean to remove the corresponding installed archive or binary (what ‘go install’ would create).

-i 标志会导致 clean 删除相应的已安装归档或二进制文件(即 go install 会创建的内容)。

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

-n 标志会导致 clean 打印它将执行的删除命令,但不实际运行这些命令。

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

-r 标志会导致 clean 递归应用到导入路径指定的包的所有依赖项。

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

-x 标志会导致 clean 在执行时打印删除命令。

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

-cache 标志会导致 clean 删除整个 go 构建缓存。

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

-testcache 标志会导致 clean 使 go 构建缓存中的所有测试结果失效。

The -modcache flag causes clean to remove the entire module download cache, including unpacked source code of versioned dependencies.

-modcache 标志会导致 clean 删除整个模块下载缓存,包括解压的版本依赖的源代码。

The -fuzzcache flag causes clean to remove files stored in the Go build cache for fuzz testing. The fuzzing engine caches files that expand code coverage, so removing them may make fuzzing less effective until new inputs are found that provide the same coverage. These files are distinct from those stored in testdata directory; clean does not remove those files.

-fuzzcache 标志会导致 clean 删除 go 构建缓存中用于模糊测试的文件。模糊测试引擎会缓存扩展代码覆盖率的文件,因此删除这些文件可能会使模糊测试效果减弱,直到找到新的输入来提供相同的覆盖率为止。这些文件与存储在 testdata 目录中的文件不同;clean 不会删除那些文件。

For more about build flags, see ‘go help build’.

​ 有关构建标志的更多信息,请参阅 ‘go help build’。

For more about specifying packages, see ‘go help packages’.

​ 有关指定包的更多信息,请参阅 ‘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 its arguments (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 打印与其参数标识的项目(包、常量、函数、类型、变量、方法或结构字段)相关的文档注释,然后显示该项目 “下” 的每个顶级项目的单行摘要(包级声明对于包、方法对于类型等)。

Doc accepts zero, one, or two arguments.

doc 接受零个、一个或两个参数。

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 package are elided from the presentation unless the -cmd flag is provided.

​ 它会打印当前目录中包的文档。如果包是一个命令(main 包),则包中的导出符号将从展示中省略,除非提供了 -cmd 标志。

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

​ 当运行一个参数时,该参数被视为待记录项目的 Go 语法表示形式。参数选择的内容取决于安装在 GOROOTGOPATH 中的内容,以及参数的形式,大致如下:

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 documentation is printed. (See the examples below.) However, if the argument starts with a capital letter 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 nearest the root and lexically first at its level of the hierarchy. The GOROOT tree is always scanned in its entirety before GOPATH.

​ 对于包,扫描顺序是按词法顺序广度优先。也就是说,展示的包是与搜索匹配并且最接近根目录且在其层级中词法顺序最靠前的包。在扫描 GOPATH 之前,始终会完全扫描 GOROOT 树。

If there is no package specified or matched, the package in the current directory is selected, so “go doc Foo” shows the documentation for symbol Foo in the current package.

​ 如果没有指定包或没有匹配到包,则选择当前目录中的包,因此 go doc Foo 会显示当前包中符号 Foo 的文档。

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

​ 包路径必须是合格路径或路径的适当后缀。go 工具的通常包机制不适用: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 match either case but upper-case letters match exactly. This means that there may be multiple matches of a lower-case argument in a package if different symbols have different cases. If this occurs, documentation for all matches is printed.

​ 在所有形式中,当匹配符号时,参数中的小写字母可以匹配大小写,但大写字母必须完全匹配。这意味着如果包中不同符号具有不同的大小写,可能会有多个匹配项。如果发生这种情况,将打印所有匹配项的文档。

Examples:

go doc
	Show documentation for current package.
	显示当前包的文档。
	
go doc Foo
	Show documentation for Foo in the current package.
	(Foo starts with a capital letter so it cannot match
	a package path.)
	显示当前包中 Foo 的文档。
	(Foo 以大写字母开头,因此无法匹配包路径。)
	
go doc encoding/json
	Show documentation for the encoding/json package.
	显示 encoding/json 包的文档。
	
go doc json
	Shorthand for encoding/json.
	encoding/json 的简写形式。
	
go doc json.Number (or go doc json.number)
	Show documentation and method summary for json.Number.
	显示 json.Number 的文档及其方法摘要。
	
go doc json.Number.Int64 (or go doc json.number.int64)
	Show documentation for json.Number's Int64 method.
	显示 json.Number 的 Int64 方法的文档。
	
go doc cmd/doc
	Show package docs for the doc command.
	显示 doc 命令的包文档。
	
go doc -cmd cmd/doc
	Show package docs and exported symbols within the doc command.
	显示 doc 命令的包文档及导出符号。
	
go doc template.new
	Show documentation for html/template's New function.
	(html/template is lexically before text/template)
	显示 html/template 的 New 函数的文档。
	(html/template 在词法上位于 text/template 之前)
	
go doc text/template.new # One argument
	Show documentation for text/template's New function.
	显示 text/template 的 New 函数的文档。
	
go doc text/template new # Two arguments
	Show documentation for text/template's New function.
	显示 text/template 的 New 函数的文档。

At least in the current tree, these invocations all print the
documentation for json.Decoder's Decode method:
至少在当前树中,这些调用都打印 json.Decoder 的 Decode 方法的文档:


go doc json.Decoder.Decode
go doc json.decoder.decode
go doc json.decode
cd go/src/encoding/json; go doc decode

Flags:

​ 标志:

-all
	Show all the documentation for the package.
	显示包的所有文档。
	
-c
	Respect case when matching symbols.
	匹配符号时区分大小写。
	
-cmd
	Treat a command (package main) like a regular package.
	Otherwise package main's exported symbols are hidden
	when showing the package's top-level documentation.
	将命令(`main` 包)视为常规包。
	否则在显示包的顶级文档时,会隐藏 `main` 包的导出符号。
	
-short
	One-line representation for each symbol.
	每个符号的单行表示。
	
-src
	Show the full source code for the symbol. This will
	display the full Go source of its declaration and
	definition, such as a function definition (including
	the body), type declaration or enclosing const
	block. The output may therefore include unexported
	details.
	显示符号的完整源代码。这将显示其声明和定义的完整 Go 源代码,
	例如函数定义(包括函数体)、类型声明或包含的常量块。
	因此,输出可能包含未导出的细节。
	
-u
	Show documentation for unexported as well as exported
	symbols, methods, and fields.
	显示未导出和导出的符号、方法和字段的文档。

打印 Go 环境信息 Print Go environment information

Usage:

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

Env prints Go environment information.

env 打印 Go 的环境信息。

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

​ 默认情况下,env 会以 shell 脚本的形式输出信息(在 Windows 上为批处理文件)。如果给定一个或多个变量名作为参数,env 将逐行打印每个指定变量的值。

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

-json 标志将以 JSON 格式而不是 shell 脚本格式输出环境信息。

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

-u 标志要求一个或多个参数,并取消使用 go env -w 设置的默认环境变量。

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

-w 标志要求以 NAME=VALUE 的形式给出一个或多个参数,并将指定环境变量的默认设置更改为给定值。

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

-changed 标志仅打印与默认值不同的设置,这些设置是在没有使用 -w 标志的情况下获得的。

For more about environment variables, see ‘go help environment’.

​ 有关环境变量的更多信息,请参见 go help environment

使用新 API 更新包 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.

fix 对由导入路径命名的包运行 Go 的修复命令。

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’.)

-fix 标志设置一个以逗号分隔的修复列表。默认值为所有已知修复。(它的值会传递给 go tool fix -r。)

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

​ 有关修复的更多信息,请参见 go doc cmd/fix。有关指定包的更多信息,请参见 go help packages

To run fix with other options, run ‘go tool fix’.

​ 要使用其他选项运行修复,请运行 go tool fix

See also: go fmt, go vet.

​ 另见:go fmtgo vet

使用 Gofmt 格式化包源文件 Gofmt (reformat) package sources

Usage:

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

Fmt runs the command ‘gofmt -l -w’ on the packages named by the import paths. It prints the names of the files that are modified.

fmt 在由导入路径命名的包上运行 gofmt -l -w 命令。它会打印被修改的文件的名称。

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

​ 有关 gofmt 的更多信息,请参见 go doc cmd/gofmt。有关指定包的更多信息,请参见 go help packages

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

-n 标志打印将要执行的命令。-x 标志在执行命令时打印命令。

The -mod flag’s value sets which module download mode to use: readonly or vendor. See ‘go help modules’ for more.

-mod 标志的值设置使用的模块下载模式:readonlyvendor。有关更多信息,请参见 go help modules

To run gofmt with specific options, run gofmt itself.

​ 要使用特定选项运行 gofmt,请直接运行 gofmt

See also: go fix, go vet.

​ 另见:go fixgo vet

通过处理源代码生成 Go 文件 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 existing files. Those commands can run any process but the intent is to create or update Go source files.

generate 运行由现有文件中的指令描述的命令。这些命令可以运行任何进程,但目的是创建或更新 Go 源文件。

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

go generate 不会被 go buildgo test 等命令自动运行。它必须显式运行。

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

go generate 会扫描文件中的指令,这些指令的格式为:

//go:generate command argument...

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

​ (注意:没有前导空格,且 //go 中没有空格),其中 command 是要运行的生成器,对应于可以在本地运行的可执行文件。它必须位于 shell 路径中(如 gofmt),或是一个完整路径(如 /usr/you/bin/mytool),或是下面描述的命令别名。

Note that go generate does not parse the file, so lines that look like directives in comments or multiline strings will be treated as directives.

​ 请注意,go generate 不会解析文件,因此在注释或多行字符串中看似指令的行也会被视为指令。

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

​ 指令的参数是空格分隔的标记或双引号字符串,当生成器运行时,这些参数将作为独立参数传递给生成器。

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

​ Quoted strings 使用 Go 语法,在执行前会进行求值;在生成器中,quoted strings 会作为一个单独的参数出现。

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

​ 为了传达给人类和机器工具代码是生成的,生成的源代码应包含一行与以下正则表达式匹配的代码(使用 Go 语法):

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

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

​ 该行必须出现在文件中的第一行非注释、非空白文本之前。

Go generate sets several variables when it runs the generator:

go generate 在运行生成器时会设置几个变量:

$GOARCH
	The execution architecture (arm, amd64, etc.)
	执行架构(arm, amd64 等)
	
$GOOS
	The execution operating system (linux, windows, etc.)
	执行操作系统(linux, windows 等)
	
$GOFILE
	The base name of the file.
	文件的基本名称。
	
$GOLINE
	The line number of the directive in the source file.
	源文件中指令的行号。
	
$GOPACKAGE
	The name of the package of the file containing the directive.
	包含指令的文件所属的包名称。
	
$GOROOT
	The GOROOT directory for the 'go' command that invoked the
	generator, containing the Go toolchain and standard library.
	调用生成器的 `go` 命令的 `GOROOT` 目录,包含 Go 工具链和标准库。
	
$DOLLAR
	A dollar sign.
	美元符号。
	
$PATH
	The $PATH of the parent process, with $GOROOT/bin
	placed at the beginning. This causes generators
	that execute 'go' commands to use the same 'go'
	as the parent 'go generate' command.
	父进程的 $PATH,其中将 $GOROOT/bin 放在开头。这将使执行 `go` 命令的生成器使用与父 `go generate` 命令相同的 `go`。
	

Other than variable substitution and quoted-string evaluation, no special processing such as “globbing” is performed on the command line.

​ 除了变量替换和 quoted-string 求值之外,命令行上没有进行特殊处理(如 “globbing”)。

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

​ 在运行命令之前的最后一步,所有带字母数字名称的环境变量的调用,例如 $GOFILE$HOME,将在整个命令行中展开。变量展开的语法在所有操作系统上均为 $NAME。由于求值顺序的原因,变量即使在 quoted strings 中也会展开。如果变量 NAME 未设置,则 $NAME 会展开为空字符串。

A directive of the form,

​ 形式为:

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

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

的指令会指定,在该源文件的剩余部分中,字符串 xxx 代表由参数标识的命令。这可以用于创建别名或处理多字生成器。例如:

//go:generate -command foo go tool foo

specifies that the command “foo” represents the generator “go tool foo”.

指定命令 “foo” 代表生成器 “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 the source files in a package in file name order, one at a time. Within a source file, generate runs generators in the order they appear in the file, one at a time. The go generate tool also sets the build tag “generate” so that files may be examined by go generate but ignored during build.

generate 按给定命令行中的顺序处理包,一个包接一个包。如果命令行列出单个目录中的 .go 文件,它们会被视为一个包。对于一个包,generate 按文件名顺序处理包中的源文件,一个文件接一个文件。在一个源文件中,generate 按顺序运行生成器,一个接一个。go generate 工具还设置了构建标记 generate,以便文件可以被 go generate 检查,但在构建期间忽略。

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

​ 对于包含无效代码的包,generate 只处理带有有效包声明的源文件。

If any generator returns an error exit status, “go generate” skips all further processing for that package.

​ 如果任何生成器返回错误退出状态,“go generate”将跳过该包的所有进一步处理。

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

​ 生成器在包的源目录中运行。

Go generate accepts two specific flags:

go generate 接受两个特定标志:

-run=""
	if non-empty, specifies a regular expression to select
	directives whose full original source text (excluding
	any trailing spaces and final newline) matches the
	expression.
	如果非空,指定一个正则表达式以选择其完整的原始源文本
	(不包括任何尾随空格和最终换行符)匹配该表达式的指令。
	
-skip=""
	if non-empty, specifies a regular expression to suppress
	directives whose full original source text (excluding
	any trailing spaces and final newline) matches the
	expression. If a directive matches both the -run and
	the -skip arguments, it is skipped.
	如果非空,指定一个正则表达式以忽略其完整的原始源文本
	(不包括任何尾随空格和最终换行符)匹配该表达式的指令。
	如果某个指令同时匹配 -run 和 -skip 参数,则该指令会被跳过。

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

​ 它还接受标准的构建标志,包括 -v、-n 和 -x。-v 标志打印处理的包和文件的名称。-n 标志打印将要执行的命令。-x 标志打印执行的命令。

For more about build flags, see ‘go help build’.

​ 有关构建标志的更多信息,请参见 ‘go help build’。

For more about specifying packages, see ‘go help packages’.

​ 有关指定包的更多信息,请参见 ‘go help packages’。

添加依赖项到当前模块并安装它们 Add dependencies to current module and install them

Usage:

go get [-t] [-u] [-v] [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 the module cache.

​ Get 将其命令行参数解析为特定模块版本的包,更新 go.mod 以要求这些版本,并将源代码下载到模块缓存中。

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 版本升级到最新发布的 Go 版本:

go get go@latest

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

​ 要将 Go 工具链升级到当前 Go 工具链的最新补丁版本:

go get toolchain@patch

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

​ 详细信息请参见 https://golang.org/ref/mod#go-get

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 the current directory. For example:

​ 在较早版本的 Go 中,‘go get’ 用于构建和安装包。现在,‘go get’ 专用于调整 go.mod 中的依赖项。‘go install’ 可用于构建和安装命令。当指定了版本时,‘go install’ 以模块感知模式运行,并忽略当前目录中的 go.mod 文件。例如:

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

See ‘go help install’ or https://golang.org/ref/mod#go-install for details.

​ 有关详细信息,请参见 ‘go help install’ 或 https://golang.org/ref/mod#go-install

‘go get’ accepts the following flags.

​ ‘go get’ 接受以下标志。

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

​ -t 标志指示 get 考虑构建命令行中指定包的测试所需的模块。

The -u flag instructs get to update modules providing dependencies of packages named on the command line to use newer minor or patch releases when available.

​ -u 标志指示 get 更新命令行中指定包的依赖项所提供的模块,以使用可用的较新次要版本或补丁版本。

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

​ -u=patch 标志(不是 -u patch)还指示 get 更新依赖项,但默认选择补丁版本。

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

​ 当 -t 和 -u 标志一起使用时,get 还将更新测试依赖项。

The -x flag prints commands as they are executed. This is useful for debugging version control commands when a module is downloaded directly from a repository.

​ -x 标志打印执行的命令。当直接从存储库下载模块时,这对于调试版本控制命令非常有用。

For more about build flags, see ‘go help build’.

​ 有关构建标志的更多信息,请参见 ‘go help build’。

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

​ 有关模块的更多信息,请参见 https://golang.org/ref/mod

For more about using ‘go get’ to update the minimum Go version and suggested Go toolchain, see https://go.dev/doc/toolchain.

​ 有关使用 ‘go get’ 更新最低 Go 版本和建议的 Go 工具链的更多信息,请参见 https://go.dev/doc/toolchain

For more about specifying packages, see ‘go help packages’.

​ 有关指定包的更多信息,请参见 ‘go help packages’。

This text describes the behavior of get using modules to manage source code and dependencies. If instead the go command is running in GOPATH mode, the details of get’s flags and effects change, as does ‘go help get’. See ‘go help gopath-get’.

​ 本文描述了使用模块管理源代码和依赖项时 get 的行为。如果 go 命令是在 GOPATH 模式下运行的,则 get 的标志和效果的详细信息会有所不同,具体请参见 ‘go help get’。参见 ‘go help gopath-get’。

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

​ 另见: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.

​ Install 编译并安装由导入路径命名的包。

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

​ 可执行文件安装在由 GOBIN 环境变量指定的目录中,如果未设置 GOPATH 环境变量,则默认为 $GOPATH/bin 或 $HOME/go/bin。$GOROOT 中的可执行文件安装在 $GOROOT/bin 或 $GOTOOLDIR,而不是 $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 current directory or any parent directory, if there is one. This is useful for installing executables without affecting the dependencies of the main module. To eliminate ambiguity about which module versions are used in the build, the arguments must satisfy the following constraints:

​ 如果参数带有版本后缀(如 @latest 或 @v1.0.0),“go install”将在模块感知模式下构建包,忽略当前目录或任何父目录中的 go.mod 文件(如果存在)。这对于安装可执行文件而不影响主模块的依赖项非常有用。为消除有关构建中使用的模块版本的歧义,参数必须满足以下约束:

  • 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.

  • 参数必须是包路径或包模式(带有 “…” 通配符)。它们不能是标准包(如 fmt)、元模式(std、cmd、all)或相对或绝对文件路径。

  • All arguments must have the same version suffix. Different queries are not allowed, even if they refer to the same version.

  • 所有参数必须具有相同的版本后缀。即使它们引用相同的版本,也不允许不同的查询。

  • All arguments must refer to packages in the same module at the same version.

  • 所有参数必须引用同一模块中相同版本的包。

  • Package path arguments must refer to main packages. Pattern arguments will only match main packages.

  • 包路径参数必须引用 main 包。模式参数将仅匹配 main 包。

  • No module is considered the “main” module. If the module containing packages named on the command line has a go.mod file, it must not contain directives (replace and exclude) that would cause it to be interpreted differently than if it were the main module. The module must not require a higher version of itself.

  • 没有模块被视为“主”模块。如果包含命令行中命名包的模块有一个 go.mod 文件,则它不得包含会导致其被解释为与主模块不同的指令(replace 和 exclude)。该模块不得要求更高版本的自身。

  • Vendor directories are not used in any module. (Vendor directories are not included in the module zip files downloaded by ‘go install’.)

  • 在任何模块中都不使用 vendor 目录。(vendor 目录不会包含在 ‘go install’ 下载的模块 zip 文件中。)

If the arguments don’t have version suffixes, “go install” may run in module-aware mode or GOPATH mode, depending on the GO111MODULE environment variable and the presence of a go.mod file. See ‘go help modules’ for details. If module-aware mode is enabled, “go install” runs in the context of the main module.

​ 如果参数没有版本后缀,“go install”可能会在模块感知模式或 GOPATH 模式下运行,具体取决于 GO111MODULE 环境变量和 go.mod 文件的存在情况。有关详细信息,请参见 ‘go help modules’。如果启用了模块感知模式,“go install”将在主模块的上下文中运行。

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

​ 当模块感知模式被禁用时,非主包会安装在 $GOPATH/pkg/$GOOS_$GOARCH 目录中。启用模块感知模式时,非主包会被构建并缓存,但不会安装。

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.

在 Go 1.20 之前,标准库会安装到 $GOROOT/pkg/$GOOS_$GOARCH 目录中。从 Go 1.20 开始,标准库会被构建并缓存,但不会安装。设置 GODEBUG=installgoroot=all 可以恢复使用 $GOROOT/pkg/$GOOS_$GOARCH

For more about build flags, see ‘go help build’.

​ 有关构建标志的更多信息,请参见 ‘go help build’。

For more about specifying packages, see ‘go help packages’.

​ 有关指定包的更多信息,请参见 ‘go help packages’。

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

​ 另见:go buildgo getgo 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 form of the output printed for each package. Other list flags, documented below, control more specific details.

list命令会列出指定的包,每行一个。最常用的选项是 -f-json,它们控制每个包的输出形式。其他选项(在下文中有详细说明)则控制更具体的细节。

The default output shows the package import path:

​ 默认输出显示包的导入路径:

bytes
encoding/json
github.com/gorilla/mux
golang.org/x/net/html

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

-f 选项指定使用包模板语法的替代输出格式。默认输出等同于 -f '{{.ImportPath}}'。传递给模板的结构体如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
type Package struct {
    Dir            string   // 包源文件所在的目录
    ImportPath     string   // 该目录下包的导入路径
    ImportComment  string   // 包声明中的导入注释路径
    Name           string   // 包名
    Doc            string   // 包的文档字符串
    Target         string   // 安装路径
    Shlib          string   // 包含此包的共享库(仅在使用 -linkshared 时设置)
    Goroot         bool     // 该包是否位于 Go root?
    Standard       bool     // 该包是否是 Go 标准库的一部分?
    Stale          bool     // 'go install' 是否对该包有操作?
    StaleReason    string   // Stale == true 的原因
    Root           string   // 包所在的 Go root 或 Go path 目录
    ConflictDir    string   // 此目录覆盖了 $GOPATH 中的 Dir
    BinaryOnly     bool     // 仅二进制包(已不再支持)
    ForTest        string   // 仅用于指定测试的包
    Export         string   // 包含导出数据的文件(使用 -export 时)
    BuildID        string   // 编译包的 Build ID(使用 -export 时)
    Module         *Module  // 包所在模块的信息(可能为 nil)
    Match          []string // 命令行模式匹配此包
    DepOnly        bool     // 包只是依赖项,不是显式列出的
    DefaultGODEBUG string   // 主包的默认 GODEBUG 设置

    // 源文件
    GoFiles           []string   // .go 源文件(不包括 CgoFiles、TestGoFiles、XTestGoFiles)
    CgoFiles          []string   // 导入 "C" 的 .go 源文件
    CompiledGoFiles   []string   // 提供给编译器的 .go 文件(使用 -compiled 时)
    IgnoredGoFiles    []string   // 因构建约束被忽略的 .go 源文件
    IgnoredOtherFiles []string   // 因构建约束被忽略的非 .go 源文件
    CFiles            []string   // .c 源文件
    CXXFiles          []string   // .cc、.cxx 和 .cpp 源文件
    MFiles            []string   // .m 源文件
    HFiles            []string   // .h、.hh、.hpp 和 .hxx 源文件
    FFiles            []string   // .f、.F、.for 和 .f90 Fortran 源文件
    SFiles            []string   // .s 源文件
    SwigFiles         []string   // .swig 文件
    SwigCXXFiles      []string   // .swigcxx 文件
    SysoFiles         []string   // 要添加到存档的 .syso 目标文件
    TestGoFiles       []string   // 包中的 _test.go 文件
    XTestGoFiles      []string   // 包外的 _test.go 文件

    // 嵌入文件
    EmbedPatterns      []string // //go:embed 模式
    EmbedFiles         []string // 与 EmbedPatterns 匹配的文件
    TestEmbedPatterns  []string // TestGoFiles 中的 //go:embed 模式
    TestEmbedFiles     []string // 与 TestEmbedPatterns 匹配的文件
    XTestEmbedPatterns []string // XTestGoFiles 中的 //go:embed 模式
    XTestEmbedFiles    []string // 与 XTestEmbedPatterns 匹配的文件

    // Cgo 指令
    CgoCFLAGS    []string // cgo:C 编译器的标志
    CgoCPPFLAGS  []string // cgo:C 预处理器的标志
    CgoCXXFLAGS  []string // cgo:C++ 编译器的标志
    CgoFFLAGS    []string // cgo:Fortran 编译器的标志
    CgoLDFLAGS   []string // cgo:链接器的标志
    CgoPkgConfig []string // cgo:pkg-config 名称

    // 依赖信息
    Imports      []string          // 该包使用的导入路径
    ImportMap    map[string]string // 源导入到 ImportPath 的映射(省略恒等条目)
    Deps         []string          // 所有(递归)导入的依赖项
    TestImports  []string          // TestGoFiles 中的导入
    XTestImports []string          // XTestGoFiles 中的导入

    // 错误信息
    Incomplete bool            // 此包或其依赖项有错误
    Error      *PackageError   // 加载包时的错误
    DepsErrors []*PackageError // 加载依赖项时的错误
}

Packages stored in vendor directories report an ImportPath that includes the path 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 these expanded import paths. See golang.org/s/go15vendor for more about vendoring.

​ 存储在 vendor 目录中的包的 ImportPath 会包含到 vendor 目录的路径(例如 "d/vendor/p" 而不是 "p"),以便 ImportPath 唯一标识给定包的副本。ImportsDepsTestImportsXTestImports 列表也包含这些扩展的导入路径。有关 vendor 的更多信息,请参阅 golang.org/s/go15vendor

The error information, if any, is

​ 错误信息(如果有)是:

1
2
3
4
5
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 discussion of list -m below.

​ 模块信息是一个 Module 结构体,定义在下面对 list -m 的讨论中。

The template function “join” calls strings.Join.

​ 模板函数 join 调用 strings.Join

The template function “context” returns the build context, defined as:

​ 模板函数 context 返回构建上下文,定义如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Context struct {
    GOARCH        string   // 目标架构
    GOOS          string   // 目标操作系统
    GOROOT        string   // Go 根目录
    GOPATH        string   // Go 路径
    CgoEnabled    bool     // 是否可以使用 cgo
    UseAllFiles   bool     // 无论 //go:build 行或文件名如何,都使用文件
    Compiler      string   // 计算目标路径时假定的编译器
    BuildTags     []string // //go:build 行中的构建约束
    ToolTags      []string // 工具链特定的构建约束
    ReleaseTags   []string // 当前版本兼容的发布版本
    InstallSuffix string   // 安装目录名称中的后缀
}

For more information about the meaning of these fields see the documentation for the go/build package’s Context type.

​ 有关这些字段含义的更多信息,请参阅 go/build 包的 Context 类型文档。

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

-json 选项会将包数据打印为 JSON 格式,而不是使用模板格式。JSON 选项可以选择性地提供一组以逗号分隔的必需字段名称作为输出。如果提供了这些必需字段,它们将始终出现在 JSON 输出中,但为了节省计算 JSON 结构的工作,其他字段可能会被省略。

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

-compiled 选项会使 listCompiledGoFiles 设置为提供给编译器的 Go 源文件。通常,这意味着它会重复列出 GoFiles,并添加通过处理 CgoFilesSwigFiles 生成的 Go 代码。Imports 列表包含 GoFilesCompiledGoFiles 的所有导入的并集。

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

-deps 选项会使 list 遍历不仅是指定的包,还包括它们的所有依赖项。它会以深度优先后序遍历的方式访问这些包,以便在列出一个包之前,确保其所有依赖项都已列出。没有在命令行上明确列出的包会将 DepOnly 字段设置为 true

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

-e 选项会更改对错误包的处理方式,那些无法找到或格式错误的包。默认情况下,list 命令会为每个错误包打印一个错误信息到标准错误,并在正常打印期间忽略该包。带 -e 选项时,错误包会像正确的包一样打印。

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

-export 标志会使 listExport 字段设置为包含给定包的最新导出信息的文件名称,并将 BuildID 字段设置为已编译包的构建 ID。

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

-find 标志会使 list 识别指定的包,但不解析它们的依赖项:ImportsDeps 列表将为空。使用 -find 标志时,-deps-test-export 命令不能使用。

The -test flag causes list to report not only the named packages but also their test binaries (for packages with tests), to convey to source code analysis tools exactly how test binaries are constructed. The reported import path for a test binary is the import path of the package followed by a “.test” suffix, as in “math/rand.test”. When building a test, it is sometimes necessary to rebuild certain dependencies specially for that test (most commonly the tested package itself). The reported import path of a package recompiled for a particular test binary is followed by a space and the name of the test binary in brackets, as in “math/rand math/rand.test” or “regexp [sort.test]”. The ForTest field is also set to the name of the package being tested (“math/rand” or “sort” in the previous examples).

-test 标志会使 list 报告不仅是指定的包,还包括它们的测试二进制文件(对于有测试的包),以便准确传达测试二进制文件是如何构建的。测试二进制文件的导入路径是包的导入路径后加上 “.test” 后缀,例如 “math/rand.test”。构建测试时,有时需要为该测试特别重新编译某些依赖项(最常见的是被测试的包本身)。为特定测试二进制文件重新编译的包的导入路径后会跟随一个空格和括号内的测试二进制文件名称,例如 “math/rand [math/rand.test]” 或 “regexp [sort.test]"。ForTest 字段还会设置为正在测试的包的名称(在前面的示例中是 “math/rand” 或 “sort”)。

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

DirTargetShlibRootConflictDirExport 文件路径都是绝对路径。

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 flags are absolute paths referring to cached copies of generated Go source files. Although they are Go source files, the paths may not end in “.go”.

​ 默认情况下,GoFilesCgoFiles 等列表保存 Dir 目录中的文件名(即相对于 Dir 的路径,而不是绝对路径)。使用 -compiled-test 标志时添加的生成文件是指向生成的 Go 源文件缓存副本的绝对路径。虽然它们是 Go 源文件,但路径可能不以 “.go” 结尾。

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

-m 标志使 list 列出模块而不是包。

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

​ 列出模块时,-f 标志仍然指定应用于 Go 结构体的格式模板,但现在是应用于 Module 结构体:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
type Module struct {
    Path       string        // 模块路径
    Query      string        // 与该版本对应的版本查询
    Version    string        // 模块版本
    Versions   []string      // 可用的模块版本
    Replace    *Module       // 被此模块替代
    Time       *time.Time    // 版本创建的时间
    Update     *Module       // 可用的更新版本(使用 -u)
    Main       bool          // 这是主模块吗?
    Indirect   bool          // 模块仅被主模块间接需要
    Dir        string        // 保存文件本地副本的目录(如果有)
    GoMod      string        // 描述模块的 go.mod 文件路径(如果有)
    GoVersion  string        // 模块中使用的 Go 版本
    Retracted  []string      // 撤回信息(使用 -retracted 或 -u 时)
    Deprecated string        // 弃用消息(如果有,使用 -u)
    Error      *ModuleError  // 加载模块时的错误
    Sum        string        // 路径、版本的校验和(如 go.sum 中)
    GoModSum   string        // go.mod 文件的校验和(如 go.sum 中)
    Origin     any           // 模块的来源
    Reuse      bool          // 旧模块信息的重用是安全的
}

type ModuleError struct {
    Err string // 错误本身
}

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

GoMod 引用的文件可能位于模块目录之外,如果模块在模块缓存中或使用了 -modfile 标志。

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

​ 默认输出是打印模块路径,然后是版本信息及替换信息(如果有)。例如,go list -m all 可能输出:

my/main/module
golang.org/x/text v0.3.0 => /tmp/text
rsc.io/pdf v0.1.1

The Module struct has a String method that formats this line of output, so that the default format is equivalent to -f ‘{{.String}}’.

Module 结构体具有 String 方法,该方法会格式化这一行输出,因此默认格式等同于 -f '{{.String}}'

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

​ 注意,当模块被替换时,它的 Replace 字段描述了替代模块,并且它的 Dir 字段设置为替代模块的源代码目录(如果存在)。(即,如果 Replace 非空,则 Dir 设置为 Replace.Dir,无法访问被替换的源代码。)

The -u flag adds information about available upgrades. When the latest version of a given module is newer than the current one, list -u sets the Module’s Update field to information about the newer module. list -u will also set the module’s Retracted field if the current version is retracted. The Module’s String method indicates an available upgrade by formatting 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:

-u 标志添加了可用更新的信息。当某个模块的最新版本比当前版本更新时,list -u 会将 ModuleUpdate 字段设置为有关该更新模块的信息。如果当前版本已被撤回,list -u 还会设置模块的 Retracted 字段。ModuleString 方法通过在当前版本后面格式化较新的版本来指示可用的升级。如果版本被撤回,则字符串后面会显示 “(retracted)"。例如,go list -m -u all 可能输出:

my/main/module
golang.org/x/text v0.3.0 [v0.4.0] => /tmp/text
rsc.io/pdf v0.1.1 (retracted) [v0.1.2]

(For tools, ‘go list -m -u -json all’ may be more convenient to parse.)

​ (对于工具来说,go list -m -u -json all 可能更方便解析。)

The -versions flag causes list to set the Module’s Versions field to a list of all known versions of that module, ordered according to semantic versioning, earliest to latest. The flag also changes the default output format to display the module path followed by the space-separated version list.

-versions 标志使 list 将模块的 Versions 字段设置为该模块所有已知版本的列表,按照语义版本顺序,从早到晚。该标志还会更改默认输出格式,显示模块路径,后跟以空格分隔的版本列表。

The -retracted flag causes list to report information about retracted module versions. When -retracted is used with -f or -json, the Retracted field will be set to a string explaining why the version was retracted. The string is taken from comments on the retract directive in the module’s go.mod file. When -retracted is used with -versions, retracted versions are listed together with unretracted versions. The -retracted flag may be used with or without -m.

-retracted 标志使 list 报告已撤回的模块版本信息。当 -retracted-f-json 一起使用时,Retracted 字段将被设置为解释版本为何被撤回的字符串。该字符串取自模块 go.mod 文件中 retract 指令的注释。当 -retracted-versions 一起使用时,已撤回的版本与未撤回的版本一起列出。-retracted 标志可以与 -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 main module and then dependencies sorted by module path. A pattern containing “…” specifies the active modules whose module 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.

list -m 的参数被解释为模块列表,而不是包。主模块是包含当前目录的模块。活动模块是主模块及其依赖项。没有参数时,list -m 显示主模块。带参数时,list -m 显示由参数指定的模块。活动模块中的任何模块都可以通过其模块路径指定。特殊模式 “all” 指定所有活动模块,首先是主模块,然后是按模块路径排序的依赖项。包含 “…” 的模式指定模块路径与该模式匹配的活动模块。path@version 形式的查询指定该查询的结果,这不局限于活动模块。有关模块查询的更多信息,请参见 go help modules

The template function “module” takes a single string argument that must be a module path or query and returns the specified module as a Module struct. If an error occurs, the result will be a Module struct with a non-nil Error field.

​ 模板函数 module 接受一个字符串参数,该参数必须是模块路径或查询,并返回指定的模块作为 Module 结构体。如果发生错误,结果将是 Error 字段非空的 Module 结构体。

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

​ 使用 -m 时,-reuse=old.json 标志接受一个文件名,该文件包含先前通过相同修改标志集(如 -u-retracted-versions)调用 go list -m -json 的输出。go 命令可能使用此文件来确定自上次调用以来模块是否未更改,并避免重新下载相关信息。未重新下载的模块将在新输出中标记为 Reuse 字段设置为 true。通常,模块缓存会自动提供这种重用;-reuse 标志在不保留模块缓存的系统上可能有用。

For more about build flags, see ‘go help build’.

​ 有关构建标志的更多信息,请参见 go help build

For more about specifying packages, see ‘go help packages’.

​ 有关指定包的更多信息,请参见 go help packages

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

​ 有关模块的更多信息,请访问 https://golang.org/ref/mod

模块维护 Module maintenance

Go mod provides access to operations on modules.

go mod 提供对模块操作的访问。

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.

​ 请注意,对模块的支持已内置于所有 go 命令中,而不仅仅是 go mod。例如,日常添加、移除、升级和降级依赖项应该使用 go get。有关模块功能概述,请参见 go help modules

Usage:

go mod <command> [arguments]

The commands are:

​ 命令包括:

download    下载模块到本地缓存 download modules to local cache
edit        从工具或脚本编辑 go.mod edit go.mod from tools or scripts
graph       打印模块依赖关系图 print module requirement graph
init        在当前目录初始化新模块 initialize new module in current directory
tidy        添加缺失的模块并删除未使用的模块 add missing and remove unused modules
vendor      创建依赖项的 vendor 副本 make vendored copy of dependencies
verify      验证依赖项内容是否符合预期 verify dependencies have expected content
why         解释为什么需要包或模块 explain why packages or modules are needed

Use “go help mod ” for more information about a command.

​ 使用 go help mod <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 selecting dependencies of the main module or module queries of the form path@version.

download 命令下载指定的模块,模块可以是选择主模块依赖的模块模式,或是类似 path@version 形式的模块查询。

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

​ 不带参数时,download 应用于构建和测试主模块中的包所需的模块:如果 Go 版本为 1.17 或更高,则只下载主模块显式要求的模块;如果 Go 版本为 1.16 或更低,则下载所有传递依赖的模块。

The go command will automatically download modules as needed during ordinary execution. The “go mod download” command is useful mainly for pre-filling the local cache or to compute the answers for a Go module proxy.

​ 在普通执行过程中,Go 命令会自动下载所需模块。go mod download 命令主要用于预填充本地缓存,或为 Go 模块代理计算答案。

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

​ 默认情况下,download 不会向标准输出写入任何内容。它可能会向标准错误输出进度消息和错误信息。

The -json flag causes download to print a sequence of JSON objects to standard output, describing each downloaded module (or failure), corresponding to this Go struct:

-json 标志使 download 打印一系列 JSON 对象到标准输出,每个对象描述一个下载的模块(或失败),对应以下 Go 结构体:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type Module struct {
    Path     string // 模块路径
    Query    string // 版本查询,对应此版本
    Version  string // 模块版本
    Error    string // 加载模块时发生的错误
    Info     string // 缓存的 .info 文件的绝对路径
    GoMod    string // 缓存的 .mod 文件的绝对路径
    Zip      string // 缓存的 .zip 文件的绝对路径
    Dir      string // 缓存的源码根目录的绝对路径
    Sum      string // 路径和版本的校验和(如 go.sum 中)
    GoModSum string // go.mod 文件的校验和(如 go.sum 中)
    Origin   any    // 模块的来源
    Reuse    bool   // 旧模块信息的重用是安全的
}

The -reuse flag accepts the name of file containing the JSON output of a previous ‘go mod download -json’ invocation. The go command may use this file to determine that a module is unchanged since the previous invocation and avoid redownloading it. Modules that are not redownloaded will be marked in the new output by setting the Reuse field to true. Normally the module cache provides this kind of reuse automatically; the -reuse flag can be useful on systems that do not preserve the module cache.

-reuse 标志接受一个文件名,该文件包含上一次执行 go mod download -json 命令的 JSON 输出。Go 命令可能会使用此文件来判断某个模块自上次调用以来是否未发生变化,从而避免重新下载它。未重新下载的模块将在新的输出中通过设置 Reuse 字段为 true 来标记。通常,模块缓存会自动提供这种重用功能;-reuse 标志在不保留模块缓存的系统上可能有用。

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

-x 标志使 download 打印它执行的命令。

See https://golang.org/ref/mod#go-mod-download for more about ‘go mod download’.

​ 有关 go mod download 的更多信息,请参阅 https://golang.org/ref/mod#go-mod-download

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

​ 有关版本查询的更多信息,请参阅 https://golang.org/ref/mod#version-queries

从工具或脚本编辑 go.mod 文件 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.

edit 提供了一个用于编辑 go.mod 的命令行接口,主要供工具或脚本使用。它仅读取 go.mod 文件;不会查找涉及模块的其他信息。默认情况下,edit 读取并写入主模块的 go.mod 文件,但可以在编辑标志后指定其他目标文件。

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 or rewrite the go.mod file. The only time this flag is needed is if no other flags are specified, as in ‘go mod edit -fmt’.

-fmt 标志重新格式化 go.mod 文件,而不进行其他更改。任何使用或重写 go.mod 文件的修改都会隐含此格式化操作。只有在未指定其他标志时,才需要此标志,如 go mod edit -fmt

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

-module 标志更改模块路径(即 go.mod 文件中的模块行)。

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

-godebug=key=value 标志添加一行 godebug key=value,并替换掉具有相同 key 的任何现有 godebug 行。

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

-dropgodebug=key 标志删除任何具有给定 key 的现有 godebug 行。

The -require=path@version and -droprequire=path flags add and drop a requirement on the given module path and version. Note that -require overrides any existing requirements on path. These flags are mainly for tools that understand the module graph. Users should prefer ‘go get path@version’ or ‘go get path@none’, which make other go.mod adjustments as needed to satisfy constraints imposed by other modules.

-require=path@version-droprequire=path 标志添加和删除对给定模块路径和版本的要求。请注意,-require 会覆盖对 path 的任何现有要求。这些标志主要供理解模块图的工具使用。用户应该优先使用 go get path@versiongo get path@none,它们会根据其他模块施加的约束做出必要的 go.mod 调整。

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’.

-go=version 标志设置预期的 Go 语言版本。该标志主要供理解 Go 版本依赖关系的工具使用。用户应该优先使用 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’.

-toolchain=version 标志设置要使用的 Go 工具链版本。该标志主要供理解 Go 版本依赖关系的工具使用。用户应该优先使用 go get toolchain@version

The -exclude=path@version and -dropexclude=path@version flags add and drop an exclusion for the given module path and version. Note that -exclude=path@version is a no-op if that exclusion already exists.

-exclude=path@version-dropexclude=path@version 标志添加和删除对给定模块路径和版本的排除。请注意,如果排除已经存在,-exclude=path@version 是一个无操作命令。

The -replace=old[@v]=new[@v] flag adds a replacement of the given module path and version pair. If the @v in old@v is omitted, a replacement without a version on the left side is added, which applies to all versions of the old module path. If the @v in new@v is omitted, the new path should be a local module root directory, not a module path. Note that -replace overrides any redundant replacements for old[@v], so omitting @v will drop existing replacements for specific versions.

-replace=old[@v]=new[@v] 标志添加对给定模块路径和版本对的替换。如果 old@v 中的 @v 省略,则会添加没有版本的替换,这将适用于 old 模块路径的所有版本。如果 new@v 中的 @v 省略,则新路径应为本地模块根目录,而不是模块路径。请注意,-replace 会覆盖对 old[@v] 的任何冗余替换,因此省略 @v 将删除现有的特定版本替换。

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

-dropreplace=old[@v] 标志删除对给定模块路径和版本对的替换。如果省略 @v,则会删除没有版本的替换。

The -retract=version and -dropretract=version flags add and drop a retraction on the given version. The version may be a single version like “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.

-retract=version-dropretract=version 标志添加和删除对给定版本的撤回。版本可以是类似 “v1.2.3” 的单个版本,也可以是类似 “[v1.1.0,v1.1.9]” 的闭合区间。请注意,如果撤回已存在,则 -retract=version 是一个无操作命令。

The -godebug, -dropgodebug, -require, -droprequire, -exclude, -dropexclude, -replace, -dropreplace, -retract, and -dropretract editing flags may be repeated, and the changes are applied in the order given.

-godebug-dropgodebug-require-droprequire-exclude-dropexclude-replace-dropreplace-retract-dropretract 编辑标志可以重复使用,并按给定顺序应用更改。

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

-print 标志以文本格式打印最终的 go.mod 文件,而不是将其写回 go.mod

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

-json 标志以 JSON 格式打印最终的 go.mod 文件,而不是将其写回 go.mod。JSON 输出对应以下 Go 类型:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
type Module struct {
	Path    string
	Version string
}

type GoMod struct {
	Module    ModPath
	Go        string
	Toolchain string
	Godebug   []Godebug
	Require   []Require
	Exclude   []Module
	Replace   []Replace
	Retract   []Retract
}

type ModPath struct {
	Path       string
	Deprecated string
}

type Godebug struct {
	Key   string
	Value string
}

type Require struct {
	Path     string
	Version  string
	Indirect bool
}

type Replace struct {
	Old Module
	New Module
}

type Retract struct {
	Low       string
	High      string
	Rationale string
}

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

​ 代表单个版本(非区间)的 Retract 条目将使 LowHigh 字段设置为相同的值。

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

​ 请注意,这只描述了 go.mod 文件本身,而不是其他间接引用的模块。要查看构建可用的完整模块集,请使用 go list -m -json all

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

edit 还提供了 -C-n-x 构建标志。

See https://golang.org/ref/mod#go-mod-edit for more about ‘go mod edit’.

​ 有关 go mod edit 的更多信息,请参阅 https://golang.org/ref/mod#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 module and one of its requirements. Each module is identified as a string of the form path@version, except for the main module, which has no @version suffix.

graph 以文本形式打印模块依赖关系图(应用替换后)。输出中的每一行包含两个用空格分隔的字段:一个模块及其依赖项。每个模块都以 path@version 形式标识,除了主模块,它没有 @version 后缀。

The -go flag causes graph to report the module graph as loaded by the given Go version, instead of the version indicated by the ‘go’ directive in the go.mod file.

-go 标志让 graph 报告由指定 Go 版本加载的模块图,而不是由 go.mod 文件中的 go 指令指定的版本。

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

-x 标志让 graph 打印其执行的命令。

See https://golang.org/ref/mod#go-mod-graph for more about ‘go mod graph’.

​ 更多关于 go mod graph 的信息,请参见 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, in effect creating a new module rooted at the current directory. The go.mod file must not already exist.

init 会在当前目录下初始化并写入一个新的 go.mod 文件,从而在当前目录下创建一个新的模块。当前目录中不应已经存在 go.mod 文件。

Init accepts one optional argument, the module path for the new module. If the module path argument is omitted, init will attempt to infer the module path using import comments in .go files, vendoring tool configuration files (like Gopkg.lock), and the current directory (if in GOPATH).

init 接受一个可选参数,即新模块的模块路径。如果未提供模块路径参数,init 将尝试使用 .go 文件中的导入注释、供应商工具配置文件(如 Gopkg.lock)和当前目录(如果位于 GOPATH 中)来推断模块路径。

See https://golang.org/ref/mod#go-mod-init for more about ‘go mod init’.

​ 更多关于 go mod init 的信息,请参见 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’s packages and dependencies, and it removes unused modules that don’t provide any relevant packages. It also adds any missing entries to go.sum and removes any unnecessary ones.

tidy 确保 go.mod 与模块中的源代码匹配。它会添加构建当前模块的包和依赖所需的任何缺失模块,并移除不提供任何相关包的未使用模块。同时,它还会向 go.sum 添加任何缺失的条目并移除任何不必要的条目。

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

-v 标志让 tidy 打印有关移除模块的信息到标准错误输出。

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

-e 标志让 tidy 尽管在加载包时遇到错误也尝试继续。

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

-diff 标志让 tidy 不修改 go.mod 或 go.sum,而是以统一 diff 格式打印所需的更改。如果 diff 结果不为空,则以非零代码退出。

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

-go 标志让 tidy 更新 go.mod 文件中的 go 指令为指定版本,这可能会改变保留在 go.mod 文件中的模块依赖项(Go 1.17 及更高版本保留更多的依赖以支持懒加载模块)。

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

-compat 标志保留 go 命令从指定 Go 主版本加载模块图所需的额外校验和,如果该版本的 go 命令从不同模块版本加载任何导入包,tidy 将报错。默认情况下,tidy 的行为类似于将 -compat 标志设置为 go.mod 文件中 go 指令指定版本的前一个版本。

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

-x 标志让 tidy 打印下载执行的命令。

See https://golang.org/ref/mod#go-mod-tidy for more about ‘go mod tidy’.

​ 更多关于 go mod tidy 的信息,请参见 go mod tidy

创建依赖项的vendor副本 Make vendored copy of dependencies

Usage:

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

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

vendor 重置主模块的 vendor 目录,以包含构建和测试主模块包所需的所有包。它不会包含被供应商化包的测试代码。

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

-v 标志让 vendor 打印供应商化模块和包的名称到标准错误输出。

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

-e 标志让 vendor 尽管在加载包时遇到错误也尝试继续。

The -o flag causes vendor to create the vendor directory at the given path instead of “vendor”. The go command can only use a vendor directory named “vendor” within the module root directory, so this flag is primarily useful for other tools.

-o 标志让 vendor 在指定路径下创建 vendor 目录,而不是在 “vendor” 目录。go 命令只能使用模块根目录中的 “vendor” 目录,因此此标志主要适用于其他工具。

See https://golang.org/ref/mod#go-mod-vendor for more about ‘go mod vendor’.

​ 更多关于 go mod vendor 的信息,请参见 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 been modified since being downloaded. If all the modules are unmodified, verify prints “all modules verified.” Otherwise it reports which modules have been changed and causes ‘go mod’ to exit with a non-zero status.

verify 检查当前模块的依赖项是否在本地下载的源缓存中未被修改。如果所有模块均未被修改,verify 会打印 “all modules verified”。否则,它会报告哪些模块发生了更改,并导致 go mod 以非零状态退出。

See https://golang.org/ref/mod#go-mod-verify for more about ‘go mod verify’.

​ 更多关于 go mod verify 的信息,请参见 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 to each of the listed packages. If the -m flag is given, why treats the arguments as a list of modules and finds a path to any package in each of the modules.

why 显示从主模块到列出的包的导入图中的最短路径。如果使用 -m 标志,why 将把参数视为模块列表,并找到通向每个模块中任意包的路径。

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

​ 默认情况下,why 查询的是通过 go list all 匹配的包的图,其中包括可达包的测试。-vendor 标志让 why 排除依赖项的测试。

The output is a sequence of stanzas, one for each package or module name on the command line, separated by blank lines. Each stanza begins with a comment line “# package” or “# module” giving the target package or module. Subsequent lines give a path through the import graph, one package per line. If the package or module is not referenced from the main module, the stanza will display a single parenthesized note indicating that fact.

​ 输出是一个序列,每个命令行上的包或模块名都有一段内容,段与段之间用空行分隔。每段内容以 # package# module 注释行开头,标识目标包或模块。后续行显示导入图中的路径,每行一个包。如果包或模块未被主模块引用,该段将显示一个括号内的说明来指示这一点。

For example:

​ 例如:

$ go mod why golang.org/x/text/language golang.org/x/text/encoding
# golang.org/x/text/language
rsc.io/quote
rsc.io/sampler
golang.org/x/text/language

# golang.org/x/text/encoding
(main module does not need package golang.org/x/text/encoding)
$

See https://golang.org/ref/mod#go-mod-why for more about ‘go mod why’.

​ 更多关于 go mod why 的信息,请参见 go mod why

工作区维护 Workspace maintenance

Work provides access to operations on workspaces.

work 提供对工作区的操作访问。

Note that support for workspaces is built into many other commands, not just ‘go work’.

​ 请注意,许多其他命令内置了对工作区的支持,而不仅仅是 go work

See ‘go help modules’ for information about Go’s module system of which workspaces are a part.

​ 关于 Go 模块系统及其工作区部分的信息,请参见 go help modules

See https://go.dev/ref/mod#workspaces for an in-depth reference on workspaces.

​ 有关工作区的详细参考,请参见 workspaces

See https://go.dev/doc/tutorial/workspaces for an introductory tutorial on workspaces.

​ 有关工作区的入门教程,请参见 tutorial/workspaces

A workspace is specified by a go.work file that specifies a set of module directories with the “use” directive. These modules are used as root modules by the go command for builds and related operations. A workspace that does not specify modules to be used cannot be used to do builds from local modules.

​ 工作区由 go.work 文件指定,其中指定了一组包含 use 指令的模块目录。这些模块被 go 命令用作构建和相关操作的根模块。不指定使用模块的工作区不能用于从本地模块进行构建。

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

go.work 文件是行导向的。每一行包含一个指令,由一个关键字后跟参数组成。例如:

go 1.18

use ../foo/bar
use ./baz

replace 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.

​ 前导关键字可以从相邻行中提取出来以创建一个块,如同 Go 导入一样。

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

The use directive specifies a module to be included in the workspace’s set of main modules. The argument to the use directive is the directory containing the module’s go.mod file.

use 指令指定要包含在工作区主模块集中的模块。use 指令的参数是包含模块的 go.mod 文件的目录。

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

go 指令指定编写该文件时的 Go 版本。未来可能会有工作区语义的更改,这些更改可能由该版本控制,但目前指定的版本没有影响。

The replace directive has the same syntax as the replace directive in a go.mod file and takes precedence over replaces in go.mod files. It is primarily intended to override conflicting replaces in different workspace modules.

replace 指令的语法与 go.mod 文件中的 replace 指令相同,并且优先于 go.mod 文件中的 replace 指令。它主要用于覆盖不同工作区模块中的冲突替换。

To determine whether the go command is operating in workspace mode, use the “go env GOWORK” command. This will specify the workspace file being used.

​ 要确定 go 命令是否在工作区模式下运行,请使用 go env GOWORK 命令。该命令将指定正在使用的工作区文件。

Usage:

go work <command> [arguments]

The commands are:

​ 命令包括:

edit        编辑 go.work 文件,供工具或脚本使用 edit go.work from tools or scripts
init        初始化工作区文件 initialize workspace file
sync        将工作区构建列表与模块同步 sync workspace build list to modules
use         将模块添加到工作区文件 add modules to workspace file
vendor      创建依赖项的供应商副本 make vendored copy of dependencies

Use “go help work ” for more information about a command.

​ 使用 go help work <command> 获取有关命令的更多信息。

编辑 go.work 文件(用于工具或脚本) 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 current directory and its parent directories

edit 提供了一个命令行界面,用于编辑 go.work 文件,主要供工具或脚本使用。它只会读取 go.work 文件,不会查找相关模块的信息。如果未指定文件,edit 将在当前目录及其父目录中查找 go.work 文件。

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 or rewrite the go.mod file. The only time this flag is needed is if no other flags are specified, as in ‘go work edit -fmt’.

-fmt 标志重新格式化 go.work 文件而不做其他更改。任何使用或重写 go.mod 文件的修改也会隐含此格式化操作。只有当未指定其他标志时,才需要使用此标志,例如在 go work edit -fmt 中。

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

-godebug=key=value 标志添加 godebug 键值行,替换任何具有相同键的现有 godebug 行。

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

-dropgodebug=key 标志删除具有指定键的现有 godebug 行。

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

-use=path-dropuse=path 标志分别向 go.work 文件中的模块目录集添加和删除 use 指令。

The -replace=old[@v]=new[@v] flag adds a replacement of the given module path and version pair. If the @v in old@v is omitted, a replacement without a version on the left side is added, which applies to all versions of the old module path. If the @v in new@v is omitted, the new path should be a local module root directory, not a module path. Note that -replace overrides any redundant replacements for old[@v], so omitting @v will drop existing replacements for specific versions.

-replace=old[@v]=new[@v] 标志为指定的模块路径和版本对添加替换。如果省略了 old@v 中的 @v,则会添加一个没有左侧版本的替换,它适用于所有版本的旧模块路径。如果省略了 new@v 中的 @v,则新路径应该是本地模块根目录,而不是模块路径。注意,-replace 会覆盖 old[@v] 的任何冗余替换,因此省略 @v 将删除针对特定版本的现有替换。

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

-dropreplace=old[@v] 标志删除指定模块路径和版本对的替换。如果省略了 @v,则删除没有左侧版本的替换。

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

-use-dropuse-replace-dropreplace 编辑标志可以重复使用,并按照指定的顺序应用更改。

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

-go=version 标志设置预期的 Go 语言版本。

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

-toolchain=name 标志设置要使用的 Go 工具链。

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

-print 标志以文本格式打印最终的 go.work 文件,而不是将其写回 go.mod

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

-json 标志以 JSON 格式打印最终的 go.work 文件,而不是将其写回 go.mod。JSON 输出对应于以下 Go 类型:

type GoWork struct {
	Go        string
	Toolchain string
	Godebug   []Godebug
	Use       []Use
	Replace   []Replace
}

type Godebug struct {
	Key   string
	Value string
}

type Use struct {
	DiskPath   string
	ModulePath string
}

type Replace struct {
	Old Module
	New Module
}

type Module struct {
	Path    string
	Version string
}

See the workspaces reference at https://go.dev/ref/mod#workspaces for more information.

​ 更多信息请参见 工作区参考文档

初始化工作区文件 Initialize workspace file

Usage:

go work init [moddirs]

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

init 在当前目录下初始化并写入一个新的 go.work 文件,实际上是在当前目录下创建一个新的工作区。

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

go work init 可以选择性地接受工作区模块的路径作为参数。如果省略参数,则会创建一个没有模块的空工作区。

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

​ 每个参数路径都会被添加到 go.work 文件中的 use 指令中。当前的 Go 版本也将被列入 go.work 文件中。

See the workspaces reference at https://go.dev/ref/mod#workspaces for more information.

​ 更多信息请参见 工作区参考文档

将工作区构建列表同步到模块 Sync workspace build list to modules

Usage:

go work sync

Sync syncs the workspace’s build list back to the workspace’s modules

sync 将工作区的构建列表同步回工作区的模块。

The workspace’s build list is the set of versions of all the (transitive) dependency modules used to do builds in the workspace. go work sync generates that build list using the Minimal Version Selection algorithm, and then syncs those versions back to each of modules specified in the workspace (with use directives).

​ 工作区的构建列表是用于在工作区中进行构建的所有(传递)依赖模块的版本集合。go work sync 使用最小版本选择算法生成该构建列表,然后将这些版本同步回工作区中指定的每个模块(使用 use 指令)。

The syncing is done by sequentially upgrading each of the dependency modules specified in a workspace module to the version in the build list if the dependency module’s version is not already the same as the build list’s version. Note that Minimal Version Selection guarantees that the build list’s version of each module is always the same or higher than that in each workspace module.

​ 同步通过按顺序升级工作区模块中指定的每个依赖模块到构建列表中的版本来完成,如果依赖模块的版本已经与构建列表中的版本相同,则不会升级。请注意,最小版本选择算法保证构建列表中每个模块的版本始终与每个工作区模块中的版本相同或更高。

See the workspaces reference at https://go.dev/ref/mod#workspaces for more information.

​ 更多信息请参见 工作区参考文档

向工作区文件添加模块 Add modules to workspace file

Usage:

go work use [-r] [moddirs]

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

use 提供了一个命令行界面,用于向 go.work 文件中添加目录(可以选择递归添加)。

A use directive will be added to the go.work file for each argument directory 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 that do not exist.

​ 如果命令行列出的参数目录存在,use 指令将被添加到 go.work 文件中;如果目录不存在,use 指令将从 go.work 文件中删除。如果剩余的 use 指令中引用的模块不存在,use 将失败。

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

use 更新 go.work 文件中的 go 行,以指定至少与所使用的模块(包括现有模块和新添加模块)的所有 go 行一样新的版本。如果没有参数,则这是 go work use 所做的唯一操作。

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

-r 标志递归搜索参数目录中的模块,use 命令将像指定参数目录一样操作。

See the workspaces reference at https://go.dev/ref/mod#workspaces for 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 packages needed to build and test all the workspace’s packages. It does not include test code for vendored packages.

vendor 重置工作区的 vendor 目录,以包含构建和测试工作区中的所有包所需的包。它不包含被供应商化包的测试代码。

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

-v 标志使 vendor 将供应商化模块和包的名称打印到标准错误输出。

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

-e 标志使 vendor 尽管在加载包时遇到错误也尝试继续。

The -o flag causes vendor to create the vendor directory at the given path instead of “vendor”. The go command can only use a vendor directory named “vendor” within the module root directory, so this flag is primarily useful for other tools.

-o 标志使 vendor 在给定路径下创建 vendor 目录,而不是在默认的 vendor 目录中。go 命令只能使用模块根目录中的 vendor 目录,因此此标志主要用于其他工具。

编译并运行 Go 程序 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 single directory, but it may also be an import path, file system path, or pattern matching a single known package, as in ‘go run .’ or ‘go run my/cmd’.

run 编译并运行指定的主 Go 包。通常,该包由单个目录中的 .go 源文件列表指定,但它也可以是导入路径、文件系统路径或匹配已知单个包的模式,例如 go run .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 in the current directory or any parent directory, if there is one. This is useful for running programs without affecting the dependencies of the main module.

​ 如果包参数有版本后缀(如 @latest@v1.0.0),go run 将在模块感知模式下构建程序,忽略当前目录或任何父目录中的 go.mod 文件(如果存在)。这对于运行程序而不影响主模块的依赖项非常有用。

If the package argument doesn’t have a version suffix, “go run” may run in module-aware mode or GOPATH mode, depending on the GO111MODULE environment variable 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 main module.

​ 如果包参数没有版本后缀,go run 可能会在模块感知模式或 GOPATH 模式下运行,这取决于 GO111MODULE 环境变量的值以及 go.mod 文件的存在情况。有关详细信息,请参见 go help modules。如果启用了模块感知模式,go run 会在主模块的上下文中运行。

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:

​ 默认情况下,go run 直接运行编译后的二进制文件:a.out arguments...。如果给出了 -exec 标志,go run 将使用 xprog 调用二进制文件:

'xprog a.out arguments...'.

If the -exec flag is not given, GOOS or GOARCH is different from the system default, and a program named go_$GOOS_$GOARCH_exec can be found on the current search path, ‘go run’ invokes the binary using that program, for example ‘go_js_wasm_exec a.out arguments…’. This allows execution of cross-compiled programs when a simulator or other execution method is available.

​ 如果未给出 -exec 标志,GOOSGOARCH 与系统默认值不同,并且在当前搜索路径中可以找到名为 go_$GOOS_$GOARCH_exec 的程序,则 go run 将使用该程序调用二进制文件,例如 go_js_wasm_exec a.out arguments...。这允许在模拟器或其他执行方法可用时执行交叉编译的程序。

By default, ‘go run’ compiles the binary without generating the information used by debuggers, to reduce build time. To include debugger information in the binary, use ‘go build’.

​ 默认情况下,go run 编译二进制文件时不会生成调试器使用的信息,以减少构建时间。要在二进制文件中包含调试器信息,请使用 go build

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

Run 的退出状态不是编译二进制文件的退出状态。

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

​ 有关构建标志的更多信息,请参见 go help build。有关指定包的更多信息,请参见 go help packages

See also: go build.

​ 另请参见:go build

管理遥测数据和设置 Manage telemetry data and settings

Usage:

go telemetry [off|local|on]

Telemetry is used to manage Go telemetry data and settings.

​ 遥测用于管理 Go 的遥测数据和设置。

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 file system, 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 system and periodically sent to https://telemetry.go.dev/. Uploaded data is used to help improve the Go toolchain and related tools, and it will be published as part of a public dataset.

​ 当遥测开启时,遥测数据会写入本地文件系统,并定期发送到 https://telemetry.go.dev/。上传的数据用于帮助改进 Go 工具链及相关工具,并将作为公共数据集的一部分发布。

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

​ 有关详细信息,请参见 https://telemetry.go.dev/privacy。这些数据的收集符合 Google 隐私政策(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”.

​ 要查看当前的遥测模式,请运行 go telemetry。要禁用遥测上传,但保留本地数据收集,请运行 go telemetry local。要启用数据收集和上传,请运行 go telemetry on。要禁用数据收集和上传,请运行 go telemetry off

See https://go.dev/doc/telemetry for more information on telemetry.

​ 有关遥测的更多信息,请参见 https://go.dev/doc/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:

go test 自动测试由导入路径指定的包。它以如下格式打印测试结果摘要:

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

followed by detailed output for each failed package.

​ 随后是每个失败包的详细输出。

‘Go test’ recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, fuzz tests 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.

go test 重新编译每个包以及名称匹配 *_test.go 文件的任何文件。这些附加文件可以包含测试函数、基准测试函数、模糊测试和示例函数。有关更多信息,请参见 go help testfunc。每个列出的包都会导致执行单独的测试二进制文件。名称以 “_"(包括 "_test.go")或 “.” 开头的文件将被忽略。

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

​ 声明包后缀为 _test 的测试文件将被编译为一个单独的包,然后与主测试二进制文件链接并运行。

The go tool will ignore a directory named “testdata”, making it available to hold ancillary data needed by the tests.

​ Go 工具将忽略名为 “testdata” 的目录,使其可用于保存测试所需的辅助数据。

As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems. If go vet finds any problems, go test reports those and does not run the test binary. Only a high-confidence subset of the default go vet checks are used. That subset is: atomic, bool, buildtags, directive, errorsas, ifaceassert, nilfunc, printf, and stringintconv. You can see the 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 all checks, use the -vet=all flag.

​ 作为构建测试二进制文件的一部分,go test 在包及其测试源文件上运行 go vet,以识别重大问题。如果 go vet 发现任何问题,go test 会报告这些问题,并且不会运行测试二进制文件。只会使用默认 go vet 检查的高置信度子集。该子集包括:atomicboolbuildtagsdirectiveerrorsasifaceassertnilfuncprintfstringintconv。您可以通过 go doc cmd/vet 查看这些和其他 vet 检查的文档。要禁用 go vet 的运行,请使用 -vet=off 标志。要运行所有检查,请使用 -vet=all 标志。

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

​ 所有测试输出和摘要行都打印到 go 命令的标准输出,即使测试将其打印到自己的标准错误。(go 命令的标准错误保留用于打印构建测试时的错误。)

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

go 命令将 $GOROOT/bin 放在测试环境的 $PATH 开头,以便执行 go 命令的测试使用与父 go test 命令相同的 go

Go test runs in two different modes:

go test 以两种不同的模式运行:

The first, called local directory mode, occurs when go test is invoked with no package arguments (for example, ‘go test’ or ‘go test -v’). In this mode, go test compiles the package sources and tests found in the current directory and then runs the resulting test binary. In this mode, caching (discussed below) is disabled. After the package test finishes, go test prints a summary line showing the test status (‘ok’ or ‘FAIL’), package name, and elapsed time.

​ 第一种称为本地目录模式,当 go test 在没有包参数的情况下调用时(例如,go testgo test -v)。在这种模式下,go test 编译当前目录中找到的包源代码和测试,然后运行生成的测试二进制文件。在这种模式下,缓存(下文讨论)被禁用。包测试完成后,go test 会打印一行摘要,显示测试状态(okFAIL)、包名称和经过时间。

The second, called package list mode, occurs when go test is invoked with explicit package arguments (for example ‘go test math’, ‘go test ./…’, and even ‘go test .’). In this mode, go test compiles and tests each of the packages listed on the command line. If a package test passes, go test prints only the final ‘ok’ summary line. If a package test fails, go test prints the full test output. If invoked with the -bench or -v flag, go test prints the full output even for passing package tests, in order to display the requested benchmark results or verbose logging. After the package tests for all of the listed packages finish, and their output is printed, go test prints a final ‘FAIL’ status if any package test has failed.

​ 第二种称为包列表模式,当 go test 被显式包参数调用时(例如,go test mathgo test ./... 甚至 go test .)。在这种模式下,go test 编译并测试命令行中列出的每个包。如果包测试通过,go test 仅打印最终的 ok 摘要行。如果包测试失败,go test 会打印完整的测试输出。如果使用 -bench-v 标志调用,go test 将打印完整的输出,即使是通过的包测试,以显示请求的基准测试结果或详细日志记录。所有列出包的包测试完成并打印其输出后,如果任何包测试失败,go test 会打印最终的 FAIL 状态。

In package list mode only, go test caches successful package test results to avoid unnecessary repeated running of tests. When the result of a test can be recovered from the cache, go test will redisplay the previous output instead of running the test binary again. When this happens, go test prints ‘(cached)’ in place of the elapsed time in the summary line.

​ 仅在包列表模式下,go test 会缓存成功的包测试结果,以避免不必要的重复运行测试。当测试结果可以从缓存中恢复时,go test 将重新显示以前的输出,而不是再次运行测试二进制文件。当发生这种情况时,go test 会在摘要行中以 (cached) 替代经过时间。

The rule for a match in the cache is that the run involves the same test binary and the flags on the command line come entirely from a restricted set of ‘cacheable’ test flags, defined as -benchtime, -cpu, -list, -parallel, -run, -short, -timeout, -failfast, -fullpath 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 flag or argument other than the cacheable flags. The idiomatic way to disable test caching explicitly is to use -count=1. Tests that open files within the package’s source root (usually $GOPATH) or that consult environment variables only match future runs in which the files and environment variables are unchanged. A cached test result is treated as executing in no time at all, so a successful package test result will be cached and reused regardless of -timeout setting.

​ 缓存匹配的规则是运行涉及相同的测试二进制文件,并且命令行上的标志完全来自一组受限的“可缓存”测试标志,定义为 -benchtime-cpu-list-parallel-run-short-timeout-failfast-fullpath-v。如果 go test 的运行具有任何超出此集合的测试或非测试标志,则结果不会被缓存。要禁用测试缓存,请使用任何测试标志或缓存以外的参数。显式禁用测试缓存的惯用方法是使用 -count=1。在包的源根目录(通常是 $GOPATH)中打开文件的测试或仅在文件和环境变量不变的情况下与未来的运行匹配。缓存的测试结果被视为在零时间内执行,因此成功的包测试结果将被缓存并重新使用,而不管 -timeout 设置如何。

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

​ 除了构建标志外,go test 自身处理的标志包括:

-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.
    将命令行的剩余部分(-args 之后的所有内容)
    传递给测试二进制文件,不进行解释和更改。
    由于此标志消耗命令行的剩余部分,
    包列表(如果存在)必须出现在此标志之前。

-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.
    将测试二进制文件编译为当前目录中的 `pkg.test`,
    但不运行它(其中 `pkg` 是包导入路径的最后一部分)。
    可以使用 `-o` 标志更改文件名或目标目录。

-exec xprog
    Run the test binary using xprog. The behavior is the same as
    in 'go run'. See 'go help run' for details.
    使用 `xprog` 运行测试二进制文件。行为与
    `go run` 中的行为相同。有关详细信息,请参见 `go help run`。

-json
    Convert test output to JSON suitable for automated processing.
    See 'go doc test2json' for the encoding details.
    将测试输出转换为适合自动处理的 JSON 格式。
    有关编码的详细信息,请参见 `go doc test2json`。

-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.
    将测试二进制文件编译为指定文件。
    测试仍然运行(除非指定了 `-c` 或 `-i`)。
    如果 `file` 以斜杠结尾或指定现有目录的名称,
    测试将写入该目录中的 `pkg.test`。

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

​ 测试二进制文件还接受控制测试执行的标志;这些标志也可以通过 go test 访问。有关详细信息,请参见 go help testflag

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

​ 有关构建标志的更多信息,请参见 go help build。有关指定包的更多信息,请参见 go help packages

See also: go build, go vet.

​ 另请参见:go buildgo vet

运行指定的 Go 工具 Run specified go tool

Usage:

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

Tool runs the go tool command identified by the arguments. With no arguments it prints the list of known tools.

​ tool 会运行由参数指定的 go 工具命令。如果没有参数,它将打印已知工具的列表。

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

​ -n 标志会使工具打印将要执行的命令,但不实际执行。

For more about each tool command, see ‘go doc cmd/’.

​ 有关每个工具命令的更多信息,请参见“go doc cmd/”。

打印 Go 版本 Print Go version

Usage:

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

Version prints the build information for Go binary files.

​ version 会打印 Go 二进制文件的构建信息。

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

​ Go version 报告用于构建每个指定文件的 Go 版本。

If no files are named on the command line, go version prints its own version information.

​ 如果命令行中没有指定文件,go version 会打印其自身的版本信息。

If a directory is named, go version walks that directory, recursively, looking for recognized Go binaries and reporting their versions. By default, go version does not report unrecognized files found during a directory scan. The -v flag causes it to report unrecognized files.

​ 如果指定了一个目录,go version 会递归地扫描该目录,寻找已识别的 Go 二进制文件并报告其版本。默认情况下,go version 不会报告在目录扫描过程中找到的未识别文件。-v 标志会使它报告未识别的文件。

The -m flag causes go version to print each file’s embedded module version information, when available. In the output, the module information consists of multiple lines following the version line, each indented by a leading tab character.

​ -m 标志会使 go version 在可用时打印每个文件的嵌入模块版本信息。在输出中,模块信息会跟随在版本行之后,每行前都有一个制表符缩进。

See also: go doc runtime/debug.BuildInfo.

​ 另请参阅: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.

​ vet 会对由导入路径指定的包运行 Go vet 命令。

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’.

​ 有关 vet 及其标志的更多信息,请参见“go doc cmd/vet”。有关指定包的更多信息,请参见“go help packages”。有关检查器及其标志的列表,请参见“go tool vet help”。有关特定检查器(如“printf”)的详细信息,请参见“go tool vet help printf”。

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

​ -vettool=prog 标志选择一个不同的分析工具,具有替代或附加的检查。例如,可以使用以下命令构建并运行“shadow”分析器:

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

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

​ go vet 支持的构建标志是那些控制包解析和执行的标志,如 -C,-n,-x,-v,-tags 和 -toolexec。有关这些标志的更多信息,请参见“go help build”。

See also: go fmt, go fix.

​ 另请参阅:go fmt,go fix。

构建约束 Build constraints

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

​ 构建约束,也称为构建标签,是在某些条件下将文件包含在包中的条件。构建约束通过以下注释行给出:

//go:build

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

​ 构建约束还可以用于降低编译文件时使用的语言版本。

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

​ 约束可以出现在任何类型的源文件中(不仅仅是 Go 文件),但它们必须出现在文件的顶部附近,前面只允许有空行和其他注释。这些规则意味着在 Go 文件中,构建约束必须出现在包声明之前。

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 containing build tags combined by ||, &&, and ! operators and parentheses. Operators have the same meaning as in Go.

​ 构建约束注释被解释为包含构建标签的表达式,这些标签由 ||、&& 和 ! 运算符及括号组合。运算符的含义与 Go 中相同。

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

​ 例如,以下构建约束限制了文件在"linux"和"386"约束满足时构建,或者在"darwin"满足且"cgo"不满足时构建:

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

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

​ 文件中不能有多个 //go:build行,否则会报错。

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

​ 在特定构建期间,以下构建标签会满足:

  • the target operating system, as spelled by runtime.GOOS, set with the GOOS environment variable.
  • 目标操作系统,拼写为 runtime.GOOS,可通过 GOOS 环境变量设置。
  • the target architecture, as spelled by runtime.GOARCH, set with the GOARCH environment variable.
  • 目标架构,拼写为 runtime.GOARCH,可通过 GOARCH 环境变量设置。
  • any architecture features, in the form GOARCH.feature (for example, “amd64.v2”), as detailed below.
  • 任何架构特性,以 GOARCH.feature 形式(例如“amd64.v2”),详见下文。
  • “unix”, if GOOS is a Unix or Unix-like system.
  • 如果 GOOS 是类 Unix 系统,则为“unix”。
  • the compiler being used, either “gc” or “gccgo”
  • 正在使用的编译器,可能为“gc”或“gccgo”。
  • “cgo”, if the cgo command is supported (see CGO_ENABLED in ‘go help environment’).
  • 如果支持 cgo 命令,则为“cgo”(参见“go help environment”中的 CGO_ENABLED)。
  • 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.
  • 每个 Go 主要版本的术语,直到当前版本:“go1.1”表示从 Go 版本 1.1 开始,“go1.12”表示从 Go 1.12 开始,依此类推。
  • any additional tags given by the -tags flag (see ‘go help build’).
  • 由 -tags 标志给出的任何额外标签(参见“go help build”)。

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

​ 没有针对 Beta 版或次要版本的单独构建标签。

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

​ 如果文件名在去掉扩展名和可能的 _test 后缀后,匹配以下模式之一:

*_GOOS
*_GOARCH
*_GOOS_GOARCH

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

​ (例如:source_windows_amd64.go)其中 GOOS 和 GOARCH 分别代表任何已知的操作系统和架构值,那么该文件会被视为具有隐含的构建约束,要求这些术语(此外还有文件中的任何显式约束)。

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

​ 使用 GOOS=android 时,会同时匹配构建标签和文件,类似于 GOOS=linux 以及 android 标签和文件。

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

​ 使用 GOOS=illumos 时,会同时匹配构建标签和文件,类似于 GOOS=solaris 以及 illumos 标签和文件。

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

​ 使用 GOOS=ios 时,会同时匹配构建标签和文件,类似于 GOOS=darwin 以及 ios 标签和文件。

The defined architecture feature build tags are:

​ 定义的架构特性构建标签如下:

  • For GOARCH=386, GO386=387 and GO386=sse2 set the 386.387 and 386.sse2 build tags, respectively.
  • 对于 GOARCH=386,GO386=387 和 GO386=sse2 分别设置 386.387 和 386.sse2 构建标签。
  • For GOARCH=amd64, GOAMD64=v1, v2, and v3 correspond to the amd64.v1, amd64.v2, and amd64.v3 feature build tags.
  • 对于 GOARCH=amd64,GOAMD64=v1、v2 和 v3 分别对应 amd64.v1、amd64.v2 和 amd64.v3 特性构建标签。
  • For GOARCH=arm, GOARM=5, 6, and 7 correspond to the arm.5, arm.6, and arm.7 feature build tags.
  • 对于 GOARCH=arm,GOARM=5、6 和 7 分别对应 arm.5、arm.6 和 arm.7 特性构建标签。
  • 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.
  • 对于 GOARCH=arm64,GOARM64=v8.{0-9} 和 v9.{0-5} 分别对应 arm64.v8.{0-9} 和 arm64.v9.{0-5} 特性构建标签。
  • For GOARCH=mips or mipsle, GOMIPS=hardfloat and softfloat correspond to the mips.hardfloat and mips.softfloat (or mipsle.hardfloat and mipsle.softfloat) feature build tags.
  • 对于 GOARCH=mips 或 mipsle,GOMIPS=hardfloat 和 softfloat 分别对应 mips.hardfloat 和 mips.softfloat(或 mipsle.hardfloat 和 mipsle.softfloat)特性构建标签。
  • For GOARCH=mips64 or mips64le, GOMIPS64=hardfloat and softfloat correspond to the mips64.hardfloat and mips64.softfloat (or mips64le.hardfloat and mips64le.softfloat) feature build tags.
  • 对于 GOARCH=mips64 或 mips64le,GOMIPS64=hardfloat 和 softfloat 分别对应 mips64.hardfloat 和 mips64.softfloat(或 mips64le.hardfloat 和 mips64le.softfloat)特性构建标签。
  • For GOARCH=ppc64 or ppc64le, GOPPC64=power8, power9, and power10 correspond to the ppc64.power8, ppc64.power9, and ppc64.power10 (or ppc64le.power8, ppc64le.power9, and ppc64le.power10) feature build tags.
  • 对于 GOARCH=ppc64 或 ppc64le,GOPPC64=power8、power9 和 power10 分别对应 ppc64.power8、ppc64.power9 和 ppc64.power10(或 ppc64le.power8、ppc64le.power9 和 ppc64le.power10)特性构建标签。
  • For GOARCH=riscv64, GORISCV64=rva20u64 and rva22u64 correspond to the riscv64.rva20u64 and riscv64.rva22u64 build tags.
  • 对于 GOARCH=riscv64,GORISCV64=rva20u64 和 rva22u64 分别对应 riscv64.rva20u64 和 riscv64.rva22u64 构建标签。
  • For GOARCH=wasm, GOWASM=satconv and signext correspond to the wasm.satconv and wasm.signext feature build tags.
  • 对于 GOARCH=wasm,GOWASM=satconv 和 signext 分别对应 wasm.satconv 和 wasm.signext 特性构建标签。

For GOARCH=amd64, arm, ppc64, ppc64le, and riscv64, a particular feature level sets 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 compile when, say, GOAMD64=v4 is introduced. Code handling the absence of a particular feature level should use a negation:

​ 对于 GOARCH=amd64、arm、ppc64、ppc64le 和 riscv64,特定的特性级别会设置所有之前级别的特性构建标签。例如,GOAMD64=v2 设置 amd64.v1 和 amd64.v2 特性标志。这确保了当引入 GOAMD64=v4 时,使用 v2 特性代码仍能继续编译。处理缺少特定特性级别的代码应使用否定:

//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.)

​ (任何其他不满足的词也可以使用,但“ignore”是惯例。)

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

​ 要仅在使用 cgo 时构建文件,且仅在 Linux 和 OS X 上:

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

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

​ 这样的文件通常会与另一个实现默认功能的文件配对,后者在这种情况下将包含以下约束:

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

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

​ 命名文件为 dns_windows.go 将导致它仅在为 Windows 构建包时包含;类似地,math_386.s 将仅在为 32 位 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:build constraint when encountering the older syntax.

​ Go 1.16 及之前的版本使用了不同的构建约束语法,前缀为 “// +build”。当 gofmt 遇到旧语法时,它会添加等效的//go:build约束。

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

​ 在 Go 版本为 1.21 或更高的模块中,如果文件的构建约束包含 Go 主要版本的术语,则在编译该文件时使用的语言版本将是构建约束所隐含的最低版本。

构建模式 Build modes

The ‘go build’ and ‘go install’ commands take a -buildmode argument which indicates which kind of object file is to be built. Currently supported values are:

​ ‘go build’ 和 ‘go install’ 命令接受 -buildmode 参数,该参数指示要构建的目标文件类型。当前支持的值包括:

-buildmode=archive
	Build the listed non-main packages into .a files. Packages named
	main are ignored.
	将列出的非 main 包构建为 .a 文件。名为 main 的包将被忽略。

-buildmode=c-archive
	Build the listed main package, plus all packages it imports,
	into a C archive file. The only callable symbols will be those
	functions exported using a cgo //export comment. Requires
	exactly one main package to be listed.
	将列出的 main 包及其导入的所有包构建为 C 存档文件。唯一可调用的符号将是使用 cgo //export 注释导出的函数。要求只列出一个 main 包。

-buildmode=c-shared
	Build the listed main package, plus all packages it imports,
	into a C shared library. The only callable symbols will
	be those functions exported using a cgo //export comment.
	Requires exactly one main package to be listed.
	将列出的 main 包及其导入的所有包构建为 C 共享库。唯一可调用的符号将是使用 cgo //export 注释导出的函数。要求只列出一个 main 包。

-buildmode=default
	Listed main packages are built into executables and listed
	non-main packages are built into .a files (the default
	behavior).
	将列出的 main 包构建为可执行文件,将列出的非 main 包构建为 .a 文件(默认行为)。

-buildmode=shared
	Combine all the listed non-main packages into a single shared
	library that will be used when building with the -linkshared
	option. Packages named main are ignored.
	将所有列出的非 main 包合并为一个共享库,在使用 -linkshared 选项进行构建时使用。名为 main 的包将被忽略。

-buildmode=exe
	Build the listed main packages and everything they import into
	executables. Packages not named main are ignored.
	将列出的 main 包及其导入的所有包构建为可执行文件。名为 main 的包将被忽略。

-buildmode=pie
	Build the listed main packages and everything they import into
	position independent executables (PIE). Packages not named
	main are ignored.
	将列出的 main 包及其导入的所有包构建为位置无关的可执行文件(PIE)。名为 main 的包将被忽略。

-buildmode=plugin
	Build the listed main packages, plus all packages that they
	import, into a Go plugin. Packages not named main are ignored.
	将列出的 main 包及其导入的所有包构建为 Go 插件。名为 main 的包将被忽略。

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.

​ 在 AIX 上,链接使用 -buildmode=c-archive 构建的 Go 存档文件的 C 程序时,必须向 C 编译器传递 -Wl,-bnoobjreorder。

Go 和 C 之间的调用 Calling between Go and C

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

​ 在 Go 和 C/C++ 代码之间调用有两种不同的方法。

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

​ 第一种是 cgo 工具,它是 Go 发行版的一部分。有关如何使用它的信息,请参见 cgo 文档(go doc cmd/cgo)。

The second is the SWIG program, which is a general tool for interfacing between languages. For information on SWIG see http://swig.org/. When running go build, any file with a .swig extension will be passed to SWIG. Any file with a .swigcxx extension will be passed to SWIG with the -c++ option.

​ 第二种是 SWIG 程序,它是一种用于不同语言之间接口的通用工具。有关 SWIG 的信息,请参见 http://swig.org/。运行 go build 时,任何带有 .swig 扩展名的文件都将传递给 SWIG。任何带有 .swigcxx 扩展名的文件都将使用 -c++ 选项传递给 SWIG。

When either cgo or SWIG is used, go build will pass any .c, .m, .s, .S or .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 determine the C or C++ compiler, respectively, to use.

​ 使用 cgo 或 SWIG 时,go build 会将任何 .c、.m、.s、.S 或 .sx 文件传递给 C 编译器,将任何 .cc、.cpp、.cxx 文件传递给 C++ 编译器。可以设置 CC 或 CXX 环境变量来分别确定要使用的 C 或 C++ 编译器。

构建和测试缓存 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-build in the standard user cache directory for the current operating system. Setting the GOCACHE environment variable overrides this default, and running ‘go env GOCACHE’ prints the current cache directory.

​ go 命令会缓存构建输出,以便在将来的构建中重用。缓存数据的默认位置是当前操作系统的标准用户缓存目录中的一个名为 go-build 的子目录。设置 GOCACHE 环境变量可以覆盖此默认值,运行 ‘go env GOCACHE’ 会打印当前的缓存目录。

The go command periodically deletes cached data that has not been used recently. Running ‘go clean -cache’ deletes all cached data.

​ go 命令会定期删除最近未使用的缓存数据。运行 ‘go clean -cache’ 可以删除所有缓存的数据。

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

​ 构建缓存会正确处理 Go 源文件、编译器、编译器选项等的更改:在典型使用中不需要显式清理缓存。然而,构建缓存不会检测到使用 cgo 导入的 C 库的更改。如果您对系统上的 C 库进行了更改,您将需要显式清理缓存,或者使用 -a 构建标志(请参阅 ‘go help build’)来强制重新构建依赖于已更新的 C 库的包。

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

​ go 命令还会缓存成功的包测试结果。有关详细信息,请参阅 ‘go help test’。运行 ‘go clean -testcache’ 会删除所有缓存的测试结果(但不会删除缓存的构建结果)。

The go command also caches values used in fuzzing with ‘go test -fuzz’, specifically, values that expanded code coverage when passed to a fuzz function. These values are not used for regular building and testing, 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.

​ go 命令还会缓存使用 ‘go test -fuzz’ 进行模糊测试时使用的值,特别是那些在传递给模糊测试函数时扩展了代码覆盖率的值。这些值不用于常规的构建和测试,但它们会存储在构建缓存的子目录中。运行 ‘go clean -fuzzcache’ 会删除所有缓存的模糊测试值。这可能会暂时降低模糊测试的效果。

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

​ 可以通过设置 GODEBUG 环境变量来启用打印有关缓存状态的调试信息:

  • GODEBUG=gocacheverify=1 causes the go command to bypass the use of any cache entries and instead rebuild everything and check that the results match existing cache entries.

  • GODEBUG=gocacheverify=1 会使 go 命令绕过任何缓存条目的使用,重新构建所有内容并检查结果是否与现有的缓存条目匹配。

  • GODEBUG=gocachehash=1 causes the go command to print the inputs for 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=gocachehash=1 会使 go 命令打印用于构建缓存查找键的所有内容哈希的输入。输出非常庞大,但对于调试缓存可能很有用。

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

  • GODEBUG=gocachetest=1 会使 go 命令打印其是否重用缓存测试结果的决策的详细信息。

环境变量 Environment variables

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

​ go 命令及其调用的工具会通过环境变量进行配置。如果环境变量未设置或为空,go 命令将使用合理的默认设置。要查看变量 的有效设置,运行 ‘go env ’。要更改默认设置,运行 ‘go env -w =’。使用 ‘go env -w’ 更改的默认设置将记录在存储于每用户配置目录中的 Go 环境配置文件中,os.UserConfigDir 会报告该目录的位置。可以通过设置 GOENV 环境变量来更改配置文件的位置,运行 ‘go env GOENV’ 会打印有效的位置,但 ‘go env -w’ 无法更改默认位置。有关详细信息,请参阅 ‘go help env’。

General-purpose environment variables:

​ 通用环境变量:

GO111MODULE
	Controls 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.
	控制 go 命令是在模块感知模式下运行还是在 GOPATH 模式下运行。
	可以是 "off"、"on" 或 "auto"。
	参见 https://golang.org/ref/mod#mod-commands。
	
GCCGO
	The gccgo command to run for 'go build -compiler=gccgo'.
	用于 'go build -compiler=gccgo' 的 gccgo 命令。
	
GOARCH
	The architecture, or processor, for which to compile code.
	Examples are amd64, 386, arm, ppc64.
	编译代码的架构或处理器。
	例如 amd64、386、arm、ppc64。
	
GOBIN
	The directory where 'go install' will install a command.
	'go install' 命令安装命令的目录。
	
GOCACHE
	The directory where the go command will store cached
	information for reuse in future builds.
	go 命令用于存储缓存信息以便未来构建时重用的目录。
	
GOMODCACHE
	The directory where the go command will store downloaded modules.
	go 命令存储下载模块的目录。
	
GODEBUG
	Enable various debugging facilities. See https://go.dev/doc/godebug
	for details.
	启用各种调试功能。详情见 https://go.dev/doc/godebug。
	
GOENV
	The location of the Go environment configuration file.
	Cannot be set using 'go env -w'.
	Setting GOENV=off in the environment disables the use of the
	default configuration file.
	Go 环境配置文件的位置。
	不能使用 'go env -w' 设置。
	在环境中设置 GOENV=off 可禁用默认配置文件的使用。
	
GOFLAGS
	A space-separated list of -flag=value settings to apply
	to go commands by default, when the given flag is known by
	the current command. Each entry must be a standalone flag.
	Because the entries are space-separated, flag values must
	not contain spaces. Flags listed on the command line
	are applied after this list and therefore override it.
	一个空格分隔的 -flag=value 设置列表,
	默认应用于 go 命令中当前命令已知的标志。每个条目必须是独立的标志。
	由于条目是空格分隔的,标志值不能包含空格。命令行上的标志
	在该列表之后应用,因此会覆盖它。
	
GOINSECURE
	Comma-separated list of glob patterns (in the syntax of Go's path.Match)
	of module path prefixes that should always be fetched in an insecure
	manner. Only applies to dependencies that are being fetched directly.
	GOINSECURE does not disable checksum database validation. GOPRIVATE or
	GONOSUMDB may be used to achieve that.
	用逗号分隔的模块路径前缀的全局模式列表(使用 Go 的 path.Match 语法),
	这些模块始终应以不安全的方式获取。仅适用于直接获取的依赖项。
	GOINSECURE 不会禁用校验和数据库验证。可以使用 GOPRIVATE 或
	GONOSUMDB 来实现这一点。
	
GOOS
	The operating system for which to compile code.
	Examples are linux, darwin, windows, netbsd.
	编译代码的操作系统。
	例如 linux、darwin、windows、netbsd。
	
GOPATH
	Controls where various files are stored. See: 'go help gopath'.
	控制存储各种文件的位置。参见 'go help gopath'。
	
GOPROXY
	URL of Go module proxy. See https://golang.org/ref/mod#environment-variables
	and https://golang.org/ref/mod#module-proxy for details.
	Go 模块代理的 URL。详情见 https://golang.org/ref/mod#environment-variables
	和 https://golang.org/ref/mod#module-proxy。
	
GOPRIVATE, GONOPROXY, GONOSUMDB
	Comma-separated list of glob patterns (in the syntax of Go's path.Match)
	of module path prefixes that should always be fetched directly
	or that should not be compared against the checksum database.
	See https://golang.org/ref/mod#private-modules.
	用逗号分隔的模块路径前缀的全局模式列表(使用 Go 的 path.Match 语法),
	这些模块始终应直接获取,或者不应与校验和数据库进行比较。
	参见 https://golang.org/ref/mod#private-modules。
	
GOROOT
	The root of the go tree.
	Go 树的根目录。
	
GOSUMDB
	The name of checksum database to use and optionally its public key and
	URL. See https://golang.org/ref/mod#authenticating.
	要使用的校验和数据库的名称,及其公钥和 URL(如果有)。
	详情见 https://golang.org/ref/mod#authenticating。
	
GOTOOLCHAIN
	Controls which Go toolchain is used. See https://go.dev/doc/toolchain.
	控制使用哪个 Go 工具链。参见 https://go.dev/doc/toolchain。
	
GOTMPDIR
	The directory where the go command will write
	temporary source files, packages, and binaries.
	go 命令写入临时源文件、包和二进制文件的目录。
	
GOVCS
	Lists version control commands that may be used with matching servers.
	See 'go help vcs'.
	列出可以与匹配服务器一起使用的版本控制命令。
	参见 'go help vcs'。
	
GOWORK
	In 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 a
	file named go.work in the current directory and then containing directories
	until one is found. If a valid go.work file is found, the modules
	specified will collectively be used as the main modules. If GOWORK
	is "off", or a go.work file is not found in "auto" mode, workspace
	mode is disabled.
	在模块感知模式下,使用给定的 go.work 文件作为工作区文件。
	默认情况下或当 GOWORK 为 "auto" 时,go 命令会在当前目录中搜索
	名为 go.work 的文件,然后搜索包含的目录,直到找到为止。
	如果找到有效的 go.work 文件,则指定的模块将集体用作主模块。
	如果 GOWORK 为 "off",或者在 "auto" 模式下未找到 go.work 文件,
	工作区模式将被禁用。

Environment variables for use with cgo:

​ 用于 cgo 的环境变量:

AR
	The command to use to manipulate library archives when
	building with the gccgo compiler.
	The default is 'ar'.
	用于操作库档案的命令,在使用 gccgo 编译器时使用。
	默认值为 'ar'。
	
CC
	The command to use to compile C code.
	用于编译 C 代码的命令。
	
CGO_ENABLED
	Whether the cgo command is supported. Either 0 or 1.
	是否支持 cgo 命令。值为 0 或 1。
	
CGO_CFLAGS
	Flags that cgo will pass to the compiler when compiling
	C code.
	cgo 在编译 C 代码时传递给编译器的标志。
	
CGO_CFLAGS_ALLOW
	A regular expression specifying additional flags to allow
	to appear in #cgo CFLAGS source code directives.
	Does not apply to the CGO_CFLAGS environment variable.
	指定允许出现在 #cgo CFLAGS 源代码指令中的附加标志的正则表达式。
	不适用于 CGO_CFLAGS 环境变量。
	
CGO_CFLAGS_DISALLOW
	A regular expression specifying flags that must be disallowed
	from appearing in #cgo CFLAGS source code directives.
	Does not apply to the CGO_CFLAGS environment variable.
	指定禁止出现在 #cgo CFLAGS 源代码指令中的标志的正则表达式。
	不适用于 CGO_CFLAGS 环境变量。
	
CGO_CPPFLAGS, CGO_CPPFLAGS_ALLOW, CGO_CPPFLAGS_DISALLOW
	Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
	but for the C preprocessor.
	类似于 CGO_CFLAGS、CGO_CFLAGS_ALLOW 和 CGO_CFLAGS_DISALLOW,
	但适用于 C 预处理器。
	
CGO_CXXFLAGS, CGO_CXXFLAGS_ALLOW, CGO_CXXFLAGS_DISALLOW
	Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
	but for the C++ compiler.
	类似于 CGO_CFLAGS、CGO_CFLAGS_ALLOW 和 CGO_CFLAGS_DISALLOW,
	但适用于 C++ 编译器。
	
CGO_FFLAGS, CGO_FFLAGS_ALLOW, CGO_FFLAGS_DISALLOW
	Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
	but for the Fortran compiler.
	类似于 CGO_CFLAGS、CGO_CFLAGS_ALLOW 和 CGO_CFLAGS_DISALLOW,
	但适用于 Fortran 编译器。
	
CGO_LDFLAGS, CGO_LDFLAGS_ALLOW, CGO_LDFLAGS_DISALLOW
	Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
	but for the linker.
	类似于 CGO_CFLAGS、CGO_CFLAGS_ALLOW 和 CGO_CFLAGS_DISALLOW,
	但适用于链接器。
	
CXX
	The command to use to compile C++ code.
	用于编译 C++ 代码的命令。
	
FC
	The command to use to compile Fortran code.
	用于编译 Fortran 代码的命令。
	
PKG_CONFIG
	Path to pkg-config tool.
	pkg-config 工具的路径。
	

Architecture-specific environment variables:

​ 架构相关的环境变量:

GOARM
	For GOARCH=arm, the ARM architecture for which to compile.
	Valid values are 5, 6, 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).
	适用于 GOARCH=arm,用于指定编译的 ARM 架构。
	有效值为 5、6、7。
	该值可以附加一个选项,用于指定如何实现浮点指令。
	有效选项为 ,softfloat(默认值为 5)和 ,hardfloat(默认值为 6 和 7)。
	
GOARM64
	For 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.
	适用于 GOARCH=arm64,用于指定编译的 ARM64 架构。
	有效值为 v8.0(默认),v8.{1-9},v9.{0-5}。
	该值可以附加一个选项,用于指定目标硬件实现的扩展功能。
	有效选项为 ,lse 和 ,crypto。
	注意,从某个 GOARM64 版本开始,某些扩展功能默认启用;
	例如,从 v8.1 开始,lse 默认启用。
	
GO386
	For GOARCH=386, how to implement floating point instructions.
	Valid values are sse2 (default), softfloat.
	适用于 GOARCH=386,用于指定如何实现浮点指令。
	有效值为 sse2(默认)、softfloat。
	
GOAMD64
	For GOARCH=amd64, the microarchitecture level for which to compile.
	Valid values are v1 (default), v2, v3, v4.
	See https://golang.org/wiki/MinimumRequirements#amd64
	适用于 GOARCH=amd64,用于指定编译的微架构级别。
	有效值为 v1(默认)、v2、v3、v4。
	参见 https://golang.org/wiki/MinimumRequirements#amd64
	
GOMIPS
	For GOARCH=mips{,le}, whether to use floating point instructions.
	Valid values are hardfloat (default), softfloat.
	适用于 GOARCH=mips{,le},用于指定是否使用浮点指令。
	有效值为 hardfloat(默认)、softfloat。
	
GOMIPS64
	For GOARCH=mips64{,le}, whether to use floating point instructions.
	Valid values are hardfloat (default), softfloat.
	适用于 GOARCH=mips64{,le},用于指定是否使用浮点指令。
	有效值为 hardfloat(默认)、softfloat。
	
GOPPC64
	For GOARCH=ppc64{,le}, the target ISA (Instruction Set Architecture).
	Valid values are power8 (default), power9, power10.
	适用于 GOARCH=ppc64{,le},用于指定目标的 ISA(指令集架构)。
	有效值为 power8(默认)、power9、power10。
	
GORISCV64
	For GOARCH=riscv64, the RISC-V user-mode application profile for which
	to compile. Valid values are rva20u64 (default), rva22u64.
	See https://github.com/riscv/riscv-profiles/blob/main/src/profiles.adoc
	适用于 GOARCH=riscv64,用于指定编译的 RISC-V 用户模式应用配置文件。
	有效值为 rva20u64(默认)、rva22u64。
	参见 https://github.com/riscv/riscv-profiles/blob/main/src/profiles.adoc
	
GOWASM
	For GOARCH=wasm, comma-separated list of experimental WebAssembly features to use.
	Valid values are satconv, signext.
	适用于 GOARCH=wasm,用于指定使用的实验性 WebAssembly 特性,以逗号分隔的列表。
	有效值为 satconv、signext。
	

Environment variables for use with code coverage:

​ 用于代码覆盖率的环境变量:

GOCOVERDIR
	Directory into which to write code coverage data files
	generated by running a "go build -cover" binary.
	Requires that GOEXPERIMENT=coverageredesign is enabled.
	用于写入通过运行 "go build -cover" 二进制文件生成的代码覆盖率数据文件的目录。
	需要启用 GOEXPERIMENT=coverageredesign。

Special-purpose environment variables:

​ 特殊用途的环境变量:

GCCGOTOOLDIR
	If set, where to find gccgo tools, such as cgo.
	The default is based on how gccgo was configured.
	如果设置了,表示查找 gccgo 工具(如 cgo)的目录。
	默认值基于 gccgo 的配置方式。
GOEXPERIMENT
	Comma-separated list of toolchain experiments to enable or disable.
	The list of available experiments may change arbitrarily over time.
	See src/internal/goexperiment/flags.go for currently valid values.
	Warning: This variable is provided for the development and testing
	of the Go toolchain itself. Use beyond that purpose is unsupported.
	以逗号分隔的列表,用于启用或禁用工具链实验功能。
	可用实验功能列表可能会随时间任意变化。
	参见 src/internal/goexperiment/flags.go 获取当前有效值。
	警告:此变量用于 Go 工具链本身的开发和测试,超出此目的的使用不受支持
	
GO_EXTLINK_ENABLED
	Whether the linker should use external linking mode
	when using -linkmode=auto with code that uses cgo.
	Set to 0 to disable external linking mode, 1 to enable it.
	当使用 -linkmode=auto 编译包含 cgo 代码时,是否应该使用外部链接模式。
	设置为 0 以禁用外部链接模式,设置为 1 以启用它。
	
GIT_ALLOW_PROTOCOL
	Defined by Git. A colon-separated list of schemes that are allowed
	to be used with git fetch/clone. If set, any scheme not explicitly
	mentioned will be considered insecure by 'go get'.
	Because the variable is defined by Git, the default value cannot
	be set using 'go env -w'.
	由 Git 定义。一个以冒号分隔的列表,列出允许用于 git fetch/clone 的方案。
	如果设置了,任何未明确提及的方案将被 'go get' 视为不安全的。
	由于该变量由 Git 定义,因此无法使用 'go env -w' 设置默认值。
	

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

​ 从 ‘go env’ 获取的附加信息,但不是从环境中读取的:

GOEXE
	The executable file name suffix (".exe" on Windows, "" on other systems).
	可执行文件名的后缀(Windows 上为 ".exe",其他系统上为空)。
	
GOGCCFLAGS
	A space-separated list of arguments supplied to the CC command.
	传递给 CC 命令的参数的空格分隔列表。
	
GOHOSTARCH
	The architecture (GOARCH) of the Go toolchain binaries.
	Go 工具链二进制文件的架构(GOARCH)。
	
GOHOSTOS
	The operating system (GOOS) of the Go toolchain binaries.
	Go 工具链二进制文件的操作系统(GOOS)。
	
GOMOD
	The absolute path to the go.mod of the main module.
	If module-aware mode is enabled, but there is no go.mod, GOMOD will be
	os.DevNull ("/dev/null" on Unix-like systems, "NUL" on Windows).
	If module-aware mode is disabled, GOMOD will be the empty string.
	主模块的 go.mod 文件的绝对路径。
	如果启用了模块感知模式,但没有 go.mod 文件,则 GOMOD 为
	os.DevNull(Unix 类系统上为 "/dev/null",Windows 上为 "NUL")。
	如果模块感知模式被禁用,GOMOD 将为空字符串。
	
GOTOOLDIR
	The directory where the go tools (compile, cover, doc, etc...) are installed.
	安装 go 工具(如 compile、cover、doc 等)的目录。
	
GOVERSION
	The version of the installed Go tree, as reported by runtime.Version.
	已安装 Go 树的版本,由 runtime.Version 报告。

文件类型 File types

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

​ go 命令会检查每个目录中有限的一组文件的内容。它根据文件名的扩展名来确定要检查哪些文件。这些扩展名包括:

.go
	Go source files.
	Go 源文件。
	
.c, .h
	C source files.
	If the package uses cgo or SWIG, these will be compiled with the
	OS-native compiler (typically gcc); otherwise they will
	trigger an error.
	C 源文件。
	如果包使用 cgo 或 SWIG,这些文件将使用
	操作系统本机编译器(通常为 gcc)进行编译;否则将
	触发错误。
	
.cc, .cpp, .cxx, .hh, .hpp, .hxx
	C++ source files. Only useful with cgo or SWIG, and always
	compiled with the OS-native compiler.
	C++ 源文件。仅在使用 cgo 或 SWIG 时有用,并且始终
	使用操作系统本机编译器进行编译。
	
.m
	Objective-C source files. Only useful with cgo, and always
	compiled with the OS-native compiler.
	Objective-C 源文件。仅在使用 cgo 时有用,并且始终
	使用操作系统本机编译器进行编译。
	
.s, .S, .sx
	Assembler source files.
	If the package uses cgo or SWIG, these will be assembled with the
	OS-native assembler (typically gcc (sic)); otherwise they
	will be assembled with the Go assembler.
	汇编源文件。
	如果包使用 cgo 或 SWIG,这些文件将使用
	操作系统本机汇编器(通常为 gcc(sic))进行汇编;否则
	将使用 Go 汇编器进行汇编。
	
.swig, .swigcxx
	SWIG definition files.
	SWIG 定义文件。
	
.syso
	System object files.
	系统对象文件。

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

​ 除了 .syso 文件之外的每种类型文件都可以包含构建约束,但 go 命令在文件中首次遇到非空行或 // 风格的行注释时会停止扫描构建约束。有关更多详细信息,请参见 go/build 包文档。

go.mod 文件 The go.mod file

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

​ 一个模块版本由源文件树定义,根目录中包含一个 go.mod 文件。当运行 go 命令时,它会在当前目录及其父目录中查找 go.mod 文件,以标记主(当前)模块的根目录。

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

​ go.mod 文件格式的详细说明请参见 https://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’ or https://golang.org/ref/mod#go-mod-init.

​ 要创建一个新的 go.mod 文件,请使用 ‘go mod init’。有关详细信息,请参见 ‘go help mod init’ 或 https://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’ or https://golang.org/ref/mod#go-mod-tidy.

​ 要添加缺失的模块依赖或删除不需要的依赖,请使用 ‘go mod tidy’。有关详细信息,请参见 ‘go help mod tidy’ 或 https://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’ or https://golang.org/ref/mod#go-get.

​ 要添加、升级、降级或删除特定的模块依赖,请使用 ‘go get’。有关详细信息,请参见 ‘go help module-get’ 或 https://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’ or https://golang.org/ref/mod#go-mod-edit.

​ 要进行其他更改或将 go.mod 解析为 JSON 以供其他工具使用,请使用 ‘go mod edit’。请参见 ‘go help mod edit’ 或 https://golang.org/ref/mod#go-mod-edit

GOPATH 环境变量 GOPATH environment variable

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

​ Go 路径用于解析导入语句。它由 go/build 包实现并记录。

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.

​ GOPATH 环境变量列出了查找 Go 代码的路径。在 Unix 上,该值是一个以冒号分隔的字符串。在 Windows 上,该值是一个以分号分隔的字符串。在 Plan 9 上,该值是一个列表。

If the environment variable is unset, GOPATH defaults to 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.

​ 如果未设置环境变量,GOPATH 默认为用户主目录下的一个名为 “go” 的子目录(Unix 上为 $HOME/go,Windows 上为 %USERPROFILE%\go),除非该目录中存有 Go 分发包。运行 “go env GOPATH” 以查看当前的 GOPATH。

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

​ 参见 https://golang.org/wiki/SettingGOPATH 以设置自定义 GOPATH。

Each directory listed in GOPATH must have a prescribed structure:

​ GOPATH 列表中的每个目录都必须具有规定的结构:

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

​ src 目录保存源代码。src 下的路径决定了导入路径或可执行文件名称。

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

​ pkg 目录保存已安装的包对象。与 Go 树中一样,每个目标操作系统和架构对都有其自己的 pkg 子目录(pkg/GOOS_GOARCH)。

If DIR is a directory listed in the GOPATH, a package with source in DIR/src/foo/bar can be imported as “foo/bar” and has its compiled form installed to “DIR/pkg/GOOS_GOARCH/foo/bar.a”.

​ 如果 DIR 是 GOPATH 列表中的一个目录,位于 DIR/src/foo/bar 中的包可以作为 “foo/bar” 导入,并且其编译形式安装到 “DIR/pkg/GOOS_GOARCH/foo/bar.a”。

The bin directory holds compiled commands. Each command is named for its source directory, but only the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The “foo/” prefix is stripped so that you can add DIR/bin to your PATH to get at the installed commands. If the GOBIN environment variable is set, commands are installed to the directory it names instead of DIR/bin. GOBIN must be an absolute path.

bin 目录保存已编译的命令。每个命令的名称对应其源代码目录,但仅包括最后一个元素,而不是整个路径。例如,源代码位于 DIR/src/foo/quux 的命令会被安装到 DIR/bin/quux,而不是 DIR/bin/foo/quuxfoo/ 前缀会被去掉,因此你可以将 DIR/bin 添加到 PATH 中以访问已安装的命令。如果设置了 GOBIN 环境变量,命令将安装到 GOBIN 指定的目录,而不是 DIR/bin。GOBIN 必须是绝对路径。

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 directory in the list.

​ Go 会在 GOPATH 中列出的每个目录中搜索源代码,但新的包总是下载到列表中的第一个目录。

See https://golang.org/doc/code.html for an example.

​ 请参阅 https://golang.org/doc/code.html 了解示例。

GOPATH 和模块 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).

​ 使用模块时,GOPATH 不再用于解析导入路径。然而,它仍然用于存储下载的源代码(在 GOPATH/pkg/mod 中)和编译的命令(在 GOPATH/bin 中)。

内部目录 Internal Directories

Code in or below a directory named “internal” is importable only by code in the directory tree rooted at the parent of “internal”. Here’s an extended version of the directory layout above:

​ 位于名为 “internal” 的目录中的代码仅可被其父目录树中的代码导入。以下是上面目录结构的扩展版本:

/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 that import statement can only appear in source files in the subtree rooted at foo. The source files foo/f.go, foo/bar/x.go, and foo/quux/y.go can all import “foo/internal/baz”, but the source file crash/bang/b.go cannot.

z.go 中的代码可以被导入为 "foo/internal/baz",但该导入语句只能出现在 foo 子树中的源文件中。foo/f.gofoo/bar/x.gofoo/quux/y.go 文件都可以导入 "foo/internal/baz",但 crash/bang/b.go 文件不能。

See https://golang.org/s/go14internal for details.

​ 详见 https://golang.org/s/go14internal

Vendor 目录 Vendor Directories

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

​ Go 1.6 支持使用外部依赖的本地副本来满足对这些依赖的导入需求,通常称为 “vendoring”。

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

​ 位于名为 “vendor” 的目录下的代码仅可被其父目录树中的代码导入,且仅可使用省略到 vendor 元素之前的前缀的导入路径。

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:

​ 以下是上节中的示例,只不过将 “internal” 目录重命名为 “vendor”,并添加了一个新的 foo/vendor/crash/bang 目录:

/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 code in z.go is imported as “baz”, not as “foo/vendor/baz”.

​ 与 “internal” 相同的可见性规则适用,但 z.go 中的代码导入为 "baz",而不是 "foo/vendor/baz"

Code in vendor directories deeper in the source tree shadows code in higher directories. Within the subtree rooted at foo, an import of “crash/bang” resolves to “foo/vendor/crash/bang”, not the top-level “crash/bang”.

​ 源树中较深的 vendor 目录中的代码会覆盖上层目录中的代码。在以 foo 为根的子树中,导入 "crash/bang" 会解析为 "foo/vendor/crash/bang",而不是顶层的 "crash/bang"

Code in vendor directories is not subject to import path checking (see ‘go help importpath’).

vendor 目录中的代码不受导入路径检查的影响(参见 go help importpath)。

When ‘go get’ checks out or updates a git repository, it now also updates submodules.

​ 当 go get 检出或更新一个 Git 仓库时,它现在也会更新子模块。

Vendor directories do not affect the placement of new repositories being checked out for the first time by ‘go get’: those are always placed in the main GOPATH, never in a vendor subtree.

vendor 目录不会影响首次通过 go get 检出的新仓库的位置:这些仓库总是放置在主 GOPATH 中,而不是 vendor 子树中。

See https://golang.org/s/go15vendor for details.

​ 详见 https://golang.org/s/go15vendor

模块代理协议 Module proxy protocol

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

​ Go 模块代理是任何可以响应指定形式的 GET 请求的 Web 服务器。这些请求没有查询参数,因此即使是从固定文件系统提供服务的网站(包括 file:/// URL)也可以是模块代理。

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

​ 有关 GOPROXY 协议的详细信息,请参阅 https://golang.org/ref/mod#goproxy-protocol

导入路径语法 Import path syntax

An import path (see ‘go help packages’) denotes a package stored in the local file system. In general, an import path denotes either a standard package (such as “unicode/utf8”) or a package found in one of the work spaces (For more details see: ‘go help gopath’).

​ 导入路径(参见 go help packages)表示存储在本地文件系统中的包。一般来说,导入路径表示标准包(如 "unicode/utf8")或在某个工作空间中找到的包(详情请参见: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” from the “unicode/utf8” directory. Relative patterns are also allowed, like “go test ./…” to test all subdirectories. See ‘go help packages’ for details on the pattern syntax.

​ 首先,相对路径可以用作命令行中的简写。如果你在包含 "unicode" 导入代码的目录中工作,并希望运行 "unicode/utf8" 的测试,你可以输入 go test ./utf8,而无需指定完整路径。同样,在相反的情况下,go test .. 将在 "unicode/utf8" 目录中测试 "unicode"。相对模式也被允许,比如 go test ./... 来测试所有子目录。参见 go help packages 获取有关模式语法的详细信息。

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 program to refer to nearby code also not in a work space. This makes it easy to experiment with small multipackage programs outside of the usual work spaces, but such programs cannot be installed 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 paths within a work space.

​ 其次,如果你正在编译不在工作空间中的 Go 程序,你可以在该程序中的导入语句中使用相对路径来引用同样不在工作空间中的附近代码。这使得在通常的工作空间之外,可以方便地尝试小型多包程序,但这种程序无法使用 go install 安装(没有可安装的工作空间),因此每次构建时都需要从头开始重建。为了避免歧义,Go 程序不能在工作空间中使用相对导入路径。

远程导入路径 Remote import paths

Certain import paths also describe how to obtain the source code for the package using a 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 qualified with the version control type, or the go tool can dynamically fetch the import path over https/http and discover where the code resides from atag in the HTML.

​ 对于托管在其他服务器上的代码,导入路径可以加上版本控制类型的限定,或者 go 工具可以通过 https/http 动态获取导入路径,并从 HTML 中的 <meta> 标签中发现代码所在的位置。

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 inside that repository. The supported version control systems are:

​ 的导入路径指定了给定的代码库(带或不带 .vcs 后缀),并使用指定的版本控制系统,然后是该代码库内的路径。支持的版本控制系统包括:

Bazaar      .bzr
Fossil      .fossil
Git         .git
Mercurial   .hg
Subversion  .svn

For example,

​ 例如,

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

denotes the root directory of the Mercurial repository at example.org/user/foo or foo.hg, and

​ 表示位于 example.org/user/foofoo.hg 的 Mercurial 代码库的根目录,以及

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

denotes the foo/bar directory of the Git repository at example.org/repo or repo.git.

​ 表示位于 example.org/reporepo.git 的 Git 代码库的 foo/bar 目录。

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

​ 当版本控制系统支持多种协议时,每种协议在下载时会依次尝试。例如,Git 下载会依次尝试 https://git+ssh://

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

​ 默认情况下,下载操作会限制为已知的安全协议(例如 https、ssh)。要覆盖此设置以进行 Git 下载,可以设置环境变量 GIT_ALLOW_PROTOCOL(有关更多详细信息,请参阅:‘go help environment’)。

If the import path is not a known code hosting site and also lacks a version control qualifier, the go tool attempts to fetch the import over https/http and looks for atag in the document’s HTML.

​ 如果导入路径不是已知的代码托管网站,且也没有版本控制限定符,go 工具会尝试通过 https/http 获取该导入路径,并在 HTML 文档的 <head> 部分寻找 <meta> 标签。

The meta tag has the form:

​ 该 meta 标签的格式如下:

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

The import-prefix is the import path corresponding to the repository root. It must be a prefix or an exact match of the package being fetched with “go get”. If it’s not an exact match, another http request is made at the prefix to verify thetags match.

​ 其中,import-prefix 是与仓库根目录对应的导入路径。它必须是通过 go get 获取的包的前缀或完全匹配项。如果不是完全匹配,则会在该前缀处发出另一个 http 请求以验证 <meta> 标签是否匹配。

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.

​ meta 标签应尽早出现在文件中,尤其是在任何原始 JavaScript 或 CSS 之前,以避免让 go 命令的受限解析器感到困惑。

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

vcs 是 “bzr”、“fossil”、“git”、“hg”、“svn” 中的一个。

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

repo-root 是包含方案但不包含 .vcs 后缀的版本控制系统的根目录。

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 标签:

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

the go tool will verify that https://example.org/?go-get=1 contains the same meta tag and then git clone https://code.org/r/p/exproj into GOPATH/src/example.org.

​ 那么 go 工具将验证 https://example.org/?go-get=1 是否包含相同的 meta 标签,然后 git clone https://code.org/r/p/exproj 到 GOPATH/src/example.org。

When using GOPATH, downloaded packages are written to the first directory listed in the GOPATH environment variable. (See ‘go help gopath-get’ and ‘go help gopath’.)

​ 使用 GOPATH 时,下载的包将写入 GOPATH 环境变量中列出的第一个目录(详见 ‘go help gopath-get’ 和 ‘go help gopath’)。

When using modules, downloaded packages are stored in the module cache. See https://golang.org/ref/mod#module-cache.

​ 使用模块时,下载的包将存储在模块缓存中。详见 https://golang.org/ref/mod#module-cache

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

​ 使用模块时,还会识别并优先使用 go-import meta 标签的一个变体,该变体在 content 值中使用 “mod” 作为 vcs,如:

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

This tag means to fetch modules with paths beginning with example.org from the module proxy available at the URL https://code.org/moduleproxy. See https://golang.org/ref/mod#goproxy-protocol for details about the proxy protocol.

​ 此标签意味着要从位于 URL https://code.org/moduleproxy 的模块代理获取以 example.org 开头路径的模块。有关代理协议的详细信息,请参阅 https://golang.org/ref/mod#goproxy-protocol

导入路径检查 Import path checking

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

​ 当上述自定义导入路径功能重定向到已知代码托管站点时,每个生成的包都有两个可能的导入路径,使用自定义域或已知托管站点。

A package statement is said to have an “import comment” if it is immediately followed (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 comment unless it is being referred to by that import path. In this way, import comments let package authors make sure the custom import path is used and not a direct path to the underlying code hosting site.

​ go 命令将拒绝安装带有导入注释的包,除非是通过该导入路径引用它。通过这种方式,导入注释允许包作者确保使用自定义导入路径,而不是直接访问底层代码托管站点的路径。

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

​ 在 vendor 目录中的代码导入路径检查被禁用。这使得可以将代码复制到 vendor 树中的替代位置,而无需更新导入注释。

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

​ 使用模块时,导入路径检查也被禁用。导入路径注释已被 go.mod 文件的 module 声明取代。

See https://golang.org/s/go14customimport for details.

​ 详见 https://golang.org/s/go14customimport

模块、模块版本及更多内容 Modules, module versions, and more

Modules are how Go manages dependencies.

​ 模块是 Go 管理依赖关系的方式。

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

​ 模块是一起发布、版本化和分发的包集合。模块可以直接从版本控制存储库或模块代理服务器下载。

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

​ 关于模块的一系列教程,请参阅 https://golang.org/doc/tutorial/create-module

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

​ 关于模块的详细参考资料,请参阅 https://golang.org/ref/mod

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

​ 默认情况下,go 命令可以从 https://proxy.golang.org 下载模块。它可以使用位于 https://sum.golang.org 的校验和数据库对模块进行身份验证。这两个服务由 Google 的 Go 团队运营。这些服务的隐私政策可在 https://proxy.golang.org/privacyhttps://sum.golang.org/privacy 中查看。

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

​ go 命令的下载行为可以通过 GOPROXY、GOSUMDB、GOPRIVATE 和其他环境变量进行配置。请参阅 ‘go help environment’ 和 https://golang.org/ref/mod#private-module-privacy 了解更多信息。

使用 go.sum 进行模块认证 Module authentication using go.sum

When the go command downloads a module zip file or go.mod file into the module cache, it computes a cryptographic hash and compares it with a known value to verify the file hasn’t changed since it was first downloaded. Known hashes are stored in a file in the module root directory named go.sum. Hashes may also be downloaded from the checksum database depending on the values of GOSUMDB, GOPRIVATE, and GONOSUMDB.

​ 当 go 命令将模块 zip 文件或 go.mod 文件下载到模块缓存中时,它会计算一个加密哈希值,并将其与已知值进行比较,以验证该文件自首次下载以来是否没有更改。已知的哈希值存储在模块根目录中的一个名为 go.sum 的文件中。根据 GOSUMDB、GOPRIVATE 和 GONOSUMDB 的值,哈希值也可以从校验和数据库中下载。

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

​ 有关详细信息,请参阅 https://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.

​ 通常,[packages] 是一个导入路径列表。

An import path that is a rooted path or that begins with a . or .. element is interpreted as a file system path and denotes the package in that directory.

​ 一个以根路径开头或以 ... 元素开头的导入路径被解释为文件系统路径,并表示该目录中的包。

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

​ 否则,导入路径 P 表示在 GOPATH 环境变量中列出的某个目录的 DIR/src/P 目录中找到的包(有关更多详细信息,请参阅 ‘go help gopath’)。

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

​ 如果没有给出导入路径,则操作适用于当前目录中的包。

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

​ 有四个保留路径名称,不应用于使用 go 工具构建的包:

  • “main” denotes the top-level package in a stand-alone executable.

  • “main” 表示独立可执行文件中的顶级包。

  • “all” expands to all packages found in all the GOPATH trees. For example, ‘go list all’ lists all the packages on the local system. When using modules, “all” expands to all packages in the main module and their dependencies, including dependencies needed by tests of any of those.

  • “all” 扩展为在所有 GOPATH 树中找到的所有包。例如,go list all 会列出本地系统上的所有包。使用模块时,“all” 会扩展为主模块中的所有包及其依赖项,包括任何测试所需的依赖项。

  • “std” is like all but expands to just the packages in the standard Go library.

  • “std” 类似于 all,但扩展为标准 Go 库中的包。

  • “cmd” expands to the Go repository’s commands and their internal libraries.

  • “cmd” 扩展为 Go 仓库中的命令及其内部库。

Import paths beginning with “cmd/” only match source code in the Go repository.

​ 以 “cmd/” 开头的导入路径仅匹配 Go 仓库中的源代码。

An import path is a pattern if it includes one or more “…” wildcards, each of which can match any string, including the empty string and strings containing slashes. Such a pattern expands to all package directories found in the GOPATH trees with names matching the patterns.

​ 一个导入路径是一个模式,如果它包含一个或多个 ... 通配符,每个通配符可以匹配任何字符串,包括空字符串和包含斜杠的字符串。这样的模式会扩展为 GOPATH 树中所有与这些模式匹配的包目录。

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 never participates in a match of the “vendor” element in the path of a vendored package, 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 code is 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.

​ 为了使常见模式更方便使用,有两个特殊情况。首先,模式末尾的 /... 可以匹配一个空字符串,因此 net/... 可以匹配 net 以及其子目录中的包,如 net/http。其次,任何包含通配符的以斜杠分隔的模式元素都不会参与匹配被引入的包路径中的 “vendor” 元素,因此 ./... 不会匹配 ./vendor./mycode/vendor 子目录中的包,但 ./vendor/..../mycode/vendor/... 可以匹配。然而,名为 vendor 的目录如果本身包含代码,则不被视为引入的包,例如 cmd/vendor 会是一个名为 vendor 的命令,并且模式 cmd/... 可以匹配它。有关 vendoring 的更多信息,请参见 golang.org/s/go15vendor。

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

​ 导入路径也可以命名一个从远程仓库下载的包。运行 ‘go help importpath’ 了解详情。

Every package in a program must have a unique import path. By convention, this is arranged by starting each path with a unique prefix that belongs to you. For example, paths used internally at Google all begin with ‘google’, and paths denoting remote repositories begin with the path to the code, such as ‘github.com/user/repo’.

​ 程序中的每个包必须有一个唯一的导入路径。按照惯例,导入路径的开头通常是一个属于你的唯一前缀。例如,Google 内部使用的路径全部以 ‘google’ 开头,而表示远程仓库的路径以代码所在的路径开头,如 ‘github.com/user/repo’。

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 for a non-Go program in the directory. Files in package documentation are ignored by the go command.

​ 程序中的包不需要有唯一的包名,但有两个保留的包名具有特殊含义。main 表示一个命令,而不是一个库。命令被编译成二进制文件,无法被导入。documentation 表示目录中非 Go 程序的文档。go 命令会忽略 documentation 包中的文件。

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

​ 作为一个特例,如果包列表是来自单个目录的 .go 文件列表,命令将应用于由这些文件组成的一个合成包,忽略这些文件中的构建约束,并忽略目录中的其他文件。

Directory and file names that begin with “.” or “_” are ignored by the go tool, as are directories named “testdata”.

​ 以 “.” 或 “_” 开头的目录和文件名会被 go 工具忽略,同样会被忽略的还有名为 “testdata” 的目录。

下载非公开代码的配置 Configuration for downloading non-public code

The go command defaults to downloading modules from the public Go module mirror 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.

go 命令默认从公共的 Go 模块镜像 proxy.golang.org 下载模块。它还默认验证下载的模块,无论源自何处,都要与公共 Go 校验和数据库 sum.golang.org 校对。这些默认设置适用于公开的源代码。

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

GOPRIVATE 环境变量控制 go 命令认为是私有的模块(不可公开获得),因此不应使用代理或校验和数据库。该变量是一个用逗号分隔的全局模式列表(采用 Go 的 path.Match 语法),表示模块路径前缀。例如:

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

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

​ 会让 go 命令将任何路径前缀与这些模式匹配的模块视为私有,包括 git.corp.example.com/xyzzyrsc.io/privatersc.io/private/quux

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

​ 为了更细粒度地控制模块下载和验证,GONOPROXYGONOSUMDB 环境变量接受与 GOPRIVATE 相同的全局列表,并分别为是否使用代理和校验和数据库的具体决策覆盖 GOPRIVATE

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

​ 例如,如果一家公司运行了一个用于私有模块的模块代理,用户可以配置 go:

GOPRIVATE=*.corp.example.com
GOPROXY=proxy.example.com
GONOPROXY=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 paths instead of module paths.

GOPRIVATE 变量也用于为 GOVCS 变量定义“公共”和“私有”模式;参见 ‘go help vcs’。对于该用途,即使在 GOPATH 模式下,GOPRIVATE 也适用。在这种情况下,它匹配导入路径,而不是模块路径。

The ‘go env -w’ command (see ‘go help env’) can be used to set these variables for future go command invocations.

​ 可以使用 ‘go env -w’ 命令(参见 ‘go help env’)为未来的 go 命令调用设置这些变量。

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

​ 更多详情,请参见 https://golang.org/ref/mod#private-modules

测试标志 Testing flags

The ‘go test’ command takes both flags that apply to ‘go test’ itself and flags that apply to the resulting test binary.

go test 命令同时接受适用于 go test 本身的标志和适用于生成的测试二进制文件的标志。

Several of the flags control profiling and write an execution profile suitable for “go tool pprof”; run “go tool pprof -h” for more information. The –alloc_space, –alloc_objects, and –show_bytes options of pprof control how the information is presented.

​ 其中一些标志控制概要分析,并生成适用于 “go tool pprof” 的执行概要;运行 “go tool pprof -h” 了解更多信息。pprof--alloc_space--alloc_objects--show_bytes 选项控制信息的显示方式。

The following flags are recognized by the ‘go test’ command and control the execution of any test:

​ 以下标志由 go 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.
    仅运行匹配正则表达式的基准测试。
    默认情况下,不会运行任何基准测试。
    要运行所有基准测试,请使用 '-bench .' 或 '-bench=.'。
    正则表达式由未被括号包围的斜杠 (/) 字符拆分为一系列正则表达式,
    基准测试标识符的每个部分必须匹配序列中的相应元素(如果有)。
    可能的匹配父项将以 b.N=1 运行,以识别子基准测试。
    例如,给定 -bench=X/Y,匹配 X 的顶级基准测试将以 b.N=1 运行,
    以查找匹配 Y 的子基准测试,然后完整运行这些子基准测试。

-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).
    运行足够的每个基准测试迭代以花费 t 时间,指定为 time.Duration(例如,-benchtime 1h30s)。
    默认值为 1 秒 (1s)。
    特殊语法 Nx 表示运行基准测试 N 次(例如,-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.
    每个测试、基准测试和模糊测试种子运行 n 次(默认 1 次)。
    如果设置了 -cpu,针对每个 GOMAXPROCS 值运行 n 次。
    示例始终仅运行一次。-count 不适用于通过 -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.
    设置要测试的包的覆盖率分析模式。默认值为 "set",除非启用了 -race,此时默认为 "atomic"。
    取值:
	set: bool: 该语句是否运行?
	count: int: 该语句运行了多少次?
	atomic: int: 计数,但在多线程测试中正确;代价显著增加。
    设置 -cover。

-coverpkg pattern1,pattern2,pattern3
    Apply coverage analysis in each test to packages matching 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.   
    
    在每次测试中对匹配模式的包应用覆盖率分析。
    默认情况下,每个测试仅分析正在测试的包。
    请参见 'go help packages' 以了解包模式的描述。
    设置 -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.
    指定 GOMAXPROCS 值列表,测试、基准测试或模糊测试将在这些值下执行。
    默认值为当前 GOMAXPROCS 值。-cpu 不适用于通过 -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.
    运行匹配正则表达式的模糊测试。指定时,命令行参数必须精确匹配主模块中的一个包,
    regexp 必须精确匹配该包中的一个模糊测试。
    在测试、基准测试、其他模糊测试的种子语料库和示例完成后进行模糊测试。
    有关详细信息,请参阅 testing 包文档的模糊测试部分。

-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).
    在模糊测试期间,运行足够的模糊目标迭代以花费 t 时间,指定为 time.Duration(例如,-fuzztime 1h30s)。
	默认情况下,模糊测试将一直运行。
    特殊语法 Nx 表示运行模糊目标 N 次(例如,-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).
    在每次最小化尝试期间运行足够的模糊目标迭代以花费 t 时间,指定为 time.Duration(例如,-fuzzminimizetime 30s)。
	默认值为 60s。
    特殊语法 Nx 表示运行模糊目标 N 次(例如,-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.
    以 JSON 格式记录详细输出和测试结果。这提供了与 -v 标志相同的信息,但以机器可读的格式。

-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').
    允许并行执行调用 t.Parallel 的测试函数,并允许在运行种子语料库时调用 t.Parallel 的模糊目标。
    此标志的值是可以同时运行的最大测试数量。
    在模糊测试时,此标志的值是可以同时调用模糊函数的最大子进程数量,无论是否调用了 T.Parallel。
    默认情况下,-parallel 设置为 GOMAXPROCS 的值。
    将 -parallel 设置为高于 GOMAXPROCS 的值可能会导致性能下降,尤其是在进行模糊测试时。
    请注意,-parallel 仅适用于单个测试二进制文件。
    'go test' 命令也可以根据 -p 标志的设置(参见 '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.
    仅运行匹配正则表达式的测试、示例和模糊测试。
    对于测试,正则表达式由未被括号包围的斜杠 (/) 字符拆分为一系列正则表达式,
    测试标识符的每个部分必须匹配序列中的相应元素(如果有)。
    请注意,匹配的可能父项也会运行,因此 -run=X/Y 匹配并运行并报告所有匹配 X 的测试结果,
    即使没有子测试匹配 Y,因为必须运行它们以查找这些子测试。
    另请参阅 -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.
    告诉长时间运行的测试缩短其运行时间。
    默认情况下此选项关闭,但在 all.bash 期间会启用,以便在安装 Go 树时运行健全性检查,但不会花时间运行详尽的测试。

-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.
     随机化测试和基准测试的执行顺序。
    默认情况下关闭。如果 -shuffle 设置为 on,则将使用系统时钟为随机化器生成种子。
    如果 -shuffle 设置为整数 N,则将使用 N 作为种子值。在这两种情况下,都会报告种子以便重现。

-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.
    仅运行未匹配正则表达式的测试、示例、模糊测试和基准测试。
    与 -run 和 -bench 类似,对于测试和基准测试,
    正则表达式由未被括号包围的斜杠 (/) 字符拆分为一系列正则表达式,
    测试标识符的每个部分必须匹配序列中的相应元素(如果有)。

-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).
    如果测试二进制文件运行时间超过 d,则触发 panic。
    如果 d 为 0,则禁用超时。
    默认值为 10 分钟 (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.
    详细输出:记录运行的所有测试。即使测试成功,也会打印所有 Log 和 Logf 调用的文本。

-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.
    配置在 "go test" 期间调用 "go vet" 时使用的逗号分隔的检查列表。
    如果列表为空,"go test" 将使用一组认为始终值得解决的精选检查来运行 "go vet"。
    如果列表为 "off",则 "go test" 不会运行 "go vet"。

The following flags are also recognized by ‘go test’ and can be used to profile the tests during execution:

​ 以下标志也被 go test 识别,并可用于在执行过程中对测试进行概要分析:

-benchmem
    Print memory allocation statistics for benchmarks.
    Allocations made in C or using C.malloc are not counted.
    打印基准测试的内存分配统计数据。
    在 C 语言中或使用 C.malloc 进行的分配不会被计算在内。

-blockprofile block.out
    Write a goroutine blocking profile to the specified file
    when all tests are complete.
    Writes test binary as -c would.
    在所有测试完成后,将 goroutine 阻塞概要写入指定文件。
    像 -c 一样写入测试二进制文件。

-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.
    通过调用 runtime.SetBlockProfileRate 并设置 n 来控制 goroutine 阻塞概要中的详细信息。
    参见 'go doc runtime.SetBlockProfileRate'。
    概要分析器的目标是在程序阻塞的每 n 纳秒内平均采样一个阻塞事件。
    默认情况下,如果设置了 -test.blockprofile 而没有此标志,
    则会记录所有阻塞事件,相当于 -test.blockprofilerate=1。

-coverprofile cover.out
    Write a coverage profile to the file after all tests have passed.
    Sets -cover.
    在所有测试通过后,将覆盖率概要写入文件。
    设置 -cover。

-cpuprofile cpu.out
    Write a CPU profile to the specified file before exiting.
    Writes test binary as -c would.
    在退出前,将 CPU 概要写入指定文件。
    像 -c 一样写入测试二进制文件。

-memprofile mem.out
    Write an allocation profile to the file after all tests have passed.
    Writes test binary as -c would.
    在所有测试通过后,将内存分配概要写入文件。
    像 -c 一样写入测试二进制文件。

-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.
    通过设置 runtime.MemProfileRate 启用更精确(且代价更高)的内存分配概要。
    参见 'go doc runtime.MemProfileRate'。
    要分析所有内存分配,请使用 -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.
    在所有测试完成后,将互斥锁争用概要写入指定文件。
    像 -c 一样写入测试二进制文件。

-mutexprofilefraction n
    Sample 1 in n stack traces of goroutines holding a
    contended mutex.
    对持有争用互斥锁的 goroutine 的堆栈跟踪进行 1/n 的采样。

-outputdir directory
    Place output files from profiling in the specified directory,
    by default the directory in which "go test" is running.
    将概要分析生成的输出文件放在指定目录中,默认是 "go test" 运行的目录。

-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.

​ 这些标志中的每一个也可以使用可选的 test. 前缀,如 -test.v。然而,当直接调用生成的测试二进制文件(通过 go test -c 生成的结果)时,前缀是必须的。

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

go test 命令在调用测试二进制文件之前,会根据需要在可选的包列表前后重写或移除已识别的标志。

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’s execution, not to the test itself.)

​ (-x 标志会被移除,因为它只适用于 go 命令的执行,而不适用于测试本身。)

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

​ 生成概要文件的测试标志(除覆盖率之外)也会将测试二进制文件保留为 pkg.test,以便在分析概要文件时使用。

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

​ 当 go test 运行测试二进制文件时,它会在相应包的源代码目录中运行。根据测试的不同,可能需要在直接调用生成的测试二进制文件时也在该目录中运行。因为该目录可能位于只读的模块缓存中,并且由校验和验证,因此测试不能写入该目录或模块内的任何其他目录,除非用户明确请求(例如使用 -fuzz 标志,该标志会将失败结果写入 testdata/fuzz)。

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

​ 命令行中的包列表(如果存在)必须出现在 go test 命令未知的任何标志之前。继续上面的例子,包列表必须出现在 -myflag 之前,但可以出现在 -v 的任一侧。

When ‘go test’ runs in package list mode, ‘go test’ caches successful package test results to avoid unnecessary repeated running of tests. To disable test caching, use any test flag or argument other than the cacheable flags. The idiomatic way to disable test caching explicitly is to use -count=1.

​ 当 go test 以包列表模式运行时,go test 会缓存成功的包测试结果,以避免不必要的重复测试运行。要禁用测试缓存,可以使用除缓存标志以外的任何测试标志或参数。禁用测试缓存的惯用方法是使用 -count=1

To keep an argument for a test binary from being interpreted as a known flag or a package name, use -args (see ‘go help test’) which passes the remainder of the command line through to the test binary uninterpreted and unaltered.

​ 为了防止测试二进制文件的参数被解释为已知标志或包名,可以使用 -args(参见 go help test),这会将命令行的剩余部分直接传递给测试二进制文件,而不进行解释或更改。

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 the test binary unchanged and with no effect on the go command itself. In the second example, the argument math is passed through to the test binary, instead of being interpreted as the package list.

​ 在第一个例子中,-x 和第二个 -v 会被直接传递给测试二进制文件,不会对 go 命令本身产生任何影响。在第二个例子中,参数 math 被直接传递给测试二进制文件,而不是被解释为包列表。

测试函数 Testing functions

The ‘go test’ command expects to find test, benchmark, and example functions in the “*_test.go” files corresponding to the package under test.

go test 命令期望在与被测试包对应的 *_test.go 文件中找到测试、基准测试和示例函数。

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

​ 测试函数的命名应为 TestXxx(其中 Xxx 不以小写字母开头),且应具有以下签名:

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

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

​ 基准测试函数的命名应为 BenchmarkXxx,且应具有以下签名:

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

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

​ 模糊测试函数的命名应为 FuzzXxx,且应具有以下签名:

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 output is compared exactly against the comment (see examples below). If the last comment begins with “Unordered output:” then the output is compared to the comment, however the order of the lines is ignored. An example with no such comment is compiled but not executed. An example with no text after “Output:” is compiled, executed, and expected to produce no output.

​ 示例函数与测试函数类似,但不使用 *testing.T 报告成功或失败,而是将输出打印到 os.Stdout。如果函数中的最后一个注释以 “Output:” 开头,则输出将与注释内容进行精确比较(参见下面的示例)。如果最后一个注释以 “Unordered output:” 开头,则输出将与注释内容进行比较,但行的顺序将被忽略。没有此类注释的示例将被编译但不执行。没有文本跟随 “Output:” 的示例将被编译、执行,并且预期不会产生输出。

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

​ Godoc 会显示 ExampleXxx 的主体来演示函数、常量或变量 Xxx 的使用。接收器类型为 T*T 的方法 M 的示例命名为 ExampleT_M。对于给定的函数、常量或变量,可能有多个示例,它们通过尾随的 _xxx 区分,xxx 是一个不以大写字母开头的后缀。

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 single example function, at least one other function, type, variable, or constant declaration, and no tests, benchmarks, or fuzz tests.

​ 当整个测试文件包含一个示例函数、至少一个其他函数、类型、变量或常量声明,并且没有测试、基准测试或模糊测试时,整个测试文件将被视为示例。

See the documentation of the testing package for more information.

​ 有关更多信息,请参阅 testing 包的文档。

使用 GOVCS 控制版本控制 Controlling version control with GOVCS

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

go get 命令可以运行诸如 git 的版本控制命令来下载导入的代码。这一功能对于去中心化的 Go 包生态系统至关重要,因为代码可以从任何服务器导入。但这也是一个潜在的安全问题,如果恶意服务器找到方法让调用的版本控制命令运行非预期的代码。

To balance the functionality and security concerns, the ‘go get’ command by 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 packages matching the GOPRIVATE variable (see ‘go help private’). The rationale behind allowing only Git and Mercurial is that these two systems have had the most attention 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.

​ 为平衡功能性和安全性,go get 命令默认仅使用 githg 从公共服务器下载代码。但它会使用任何已知的版本控制系统(bzrfossilgithgsvn)从私人服务器下载代码,这些私人服务器是指那些托管匹配 GOPRIVATE 变量的包(参见 go help private)。只允许使用 Git 和 Mercurial 的理由是,这两个系统在作为不可信服务器的客户端时受到了最多的关注和审查。相比之下,Bazaar、Fossil 和 Subversion 主要在可信认证环境中使用,作为攻击面,它们并没有受到同样程度的审查。

The version control command restrictions only apply when using direct version control 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 private packages or when the mirror refuses to serve a public package (typically for legal reasons). Therefore, clients can still access public code served from Bazaar, Fossil, or Subversion repositories by default, because those downloads use the Go module mirror, which takes on the security risk of running the version control commands using a custom sandbox.

​ 版本控制命令限制仅适用于使用直接版本控制访问下载代码的情况。当从代理下载模块时,go get 使用的是代理协议,这始终是被允许的。默认情况下,go get 命令使用 Go 模块镜像(proxy.golang.org)来获取公共包,仅当镜像拒绝提供公共包(通常出于法律原因)时,才会回退到版本控制。因此,客户端仍然可以默认访问由 Bazaar、Fossil 或 Subversion 仓库提供的公共代码,因为这些下载使用了 Go 模块镜像,该镜像承担了在自定义沙箱中运行版本控制命令的安全风险。

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

​ 可以使用 GOVCS 变量更改特定包(由模块或导入路径标识)的允许版本控制系统。GOVCS 变量适用于模块感知模式和 GOPATH 模式下的包构建。在使用模块时,模式匹配模块路径。在使用 GOPATH 时,模式匹配与版本控制仓库根目录对应的导入路径。

The general form of the GOVCS setting is a comma-separated list of pattern:vcslist rules. The pattern is a glob pattern that must match one or more leading elements of the module or import path. The vcslist is 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 be downloaded if the origin server uses the “mod” scheme, which instructs the go command to download the module using the GOPROXY protocol. The earliest matching pattern in the list applies, even if later patterns might also match.

GOVCS 设置的一般形式为逗号分隔的模式与 vcslist 规则列表。模式是一个全局模式,必须匹配模块或导入路径的一个或多个前导元素。vcslist 是一个以管道分隔的允许版本控制命令列表,或者 “all” 表示允许使用任何已知命令,或者 “off” 表示禁用所有命令。请注意,如果模块匹配模式为 vcslist 为 “off” 的规则,如果原始服务器使用 “mod” 协议,则仍可能会下载模块,这会指示 go 命令使用 GOPROXY 协议下载模块。列表中最早匹配的模式优先适用,即使后续模式也可能匹配。

For example, consider:

​ 例如,考虑以下设置:

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

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

​ 使用此设置,以 github.com/ 开头的模块或导入路径只能使用 gitevil.com 上的路径不能使用任何版本控制命令,而所有其他路径(* 匹配所有内容)只能使用 githg

The special patterns “public” and “private” match public and private module or import paths. A path is private if it matches the GOPRIVATE variable; otherwise it is public.

​ 特殊模式 “public” 和 “private” 匹配公共和私人模块或导入路径。如果路径匹配 GOPRIVATE 变量,则为私有路径;否则为公共路径。

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 summarized in GOVCS notation as ‘public:git|hg,private:all’.

​ 如果 GOVCS 变量中的规则不匹配特定模块或导入路径,go get 命令会应用其默认规则,现在可以用 GOVCS 表示法总结为 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 GOVCS variable for future go command invocations.

​ 可以使用 go env -w 命令(参见 go help env)来设置 GOVCS 变量,以便在将来的 go 命令调用中使用。

最后修改 September 7, 2024: 更新go1.23命令 (c3aeb11)