官方资料
官方解释: https://pkg.go.dev/cmd/go#hdr-Build_constraints ,go help buildconstraint
也能看到描述
根据官方描述,go1.16
开始建议使用go:build
方式,与+build
相比更容易被人阅读。
有关go:build
注释的解析: src/go/build/build.go#shouldBuild
有关tag匹配规则: src/go/build/build.go#matchTag
下面是代码片段
func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool {
if allTags != nil {
allTags[name] = true
}
// special tags
if ctxt.CgoEnabled && name == "cgo" {
return true
}
if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
return true
}
if ctxt.GOOS == "android" && name == "linux" {
return true
}
if ctxt.GOOS == "illumos" && name == "solaris" {
return true
}
if ctxt.GOOS == "ios" && name == "darwin" {
return true
}
if name == "unix" && unixOS[ctxt.GOOS] {
return true
}
if name == "boringcrypto" {
name = "goexperiment.boringcrypto" // boringcrypto is an old name for goexperiment.boringcrypto
}
// other tags
for _, tag := range ctxt.BuildTags {
if tag == name {
return true
}
}
for _, tag := range ctxt.ToolTags {
if tag == name {
return true
}
}
for _, tag := range ctxt.ReleaseTags {
if tag == name {
return true
}
}
return false
}
在源文件src/go/build/syslist.go
中可以找到knownOS
表示tag中可以填写的OS,以及填写unix
标签时匹配的OSunixOS
,还有可填写的架构knownArch
package build
// 已知的所有OS型号
var knownOS = map[string]bool{
"aix": true,
"android": true,
"darwin": true,
"dragonfly": true,
"freebsd": true,
"hurd": true,
"illumos": true,
"ios": true,
"js": true,
"linux": true,
"nacl": true,
"netbsd": true,
"openbsd": true,
"plan9": true,
"solaris": true,
"windows": true,
"zos": true,
}
// 当使用unix时,在如下这些OS中生效
var unixOS = map[string]bool{
"aix": true,
"android": true,
"darwin": true,
"dragonfly": true,
"freebsd": true,
"hurd": true,
"illumos": true,
"ios": true,
"linux": true,
"netbsd": true,
"openbsd": true,
"solaris": true,
}
// 已知的所有架构
var knownArch = map[string]bool{
"386": true,
"amd64": true,
"amd64p32": true,
"arm": true,
"armbe": true,
"arm64": true,
"arm64be": true,
"loong64": true,
"mips": true,
"mipsle": true,
"mips64": true,
"mips64le": true,
"mips64p32": true,
"mips64p32le": true,
"ppc": true,
"ppc64": true,
"ppc64le": true,
"riscv": true,
"riscv64": true,
"s390": true,
"s390x": true,
"sparc": true,
"sparc64": true,
"wasm": true,
}
BuildTags
BuildTags
是编译命令时-tags
的参数列表,根据go help build
描述-tags
为逗号分隔字符串,兼容旧版空格分隔字符串,具体代码: src/cmd/go/internal/work/build.go#tagsFlag
因此go build -tags "a,b,c"
这种是新版推荐写法,go build -tags "a b c"
这种是旧版