Golang 开发环境中的技巧

对于Golang 开发环境相关的小的技巧很难再被记住了,所以只好收录在某处

Golang goarch list

https://stackoverflow.com/questions/20728767/all-possible-goos-value

Note that those values are defined in src/go/build/syslist.go.

With Go 1.5 (Q3 2015), GOARCH will become much more complete. See commit 1eebb91 by Minux Ma (minux)

go/build: reserve GOARCH values for all common architectures

Whenever we introduce a new GOARCH, older Go releases won’t recognize them and this causes trouble for both our users and us (we need to add unnecessary build tags).

Go 1.5 has introduced three new GOARCHes so far: arm64 ppc64 ppc64le, we can take the time to introduce GOARCHes for all common architectures that Go might support in the future to avoid the problem.

1
2
3
4
5
6
const goosList = "android darwin dragonfly freebsd linux nacl \ 
  netbsd openbsd plan9 solaris windows "

const goarchList = "386 amd64 amd64p32 arm arm64 ppc64 ppc64le \
   mips mipsle mips64 mips64le mips64p32 mips64p32le \ # (new)
   ppc s390 s390x sparc sparc64 " # (new)

The list is still being review in Change 9644, with comments like:

I wouldn’t bother with Itanium. It’s basically a dead architecture. Plus, it’s so hard to write a compiler for it that I really can’t see it happening except as a labor of love, and nobody loves the Itanium.

The official documentation now (GO 1.5+ Q3 2015) reflects that completed list.


Update 2018: as documented in Giorgos Oikonomou’s answer, Go 1.7 (Q1 2016) has introduced the go tool dist list command. See commit c3ecded: it fixes issue 12270 opened in Q3 2015:

To easier write tooling for cross compiling it would be good to programmatically get the possible combinations of GOOS and GOARCH.

This was implemented in CL 19837

cmd/dist: introduce list subcommand to list all supported platforms

You can list in plain text, or in json:

1
2
3
4
5
6
7
8
9
> go tool dist list -json
[
        {
                "GOOS": "android",
                "GOARCH": "386",
                "CgoSupported": true
        },
        ...
]

As Mark Bates tweeted:

Bonus: Column output properly formatted for display:

1
go tool dist list | column -c 75 | column -t

Golang Build Tags

build tags,

build constraints,

Excersices

  • https://www.digitalocean.com/community/tutorials/customizing-go-binaries-with-build-tags

Official

  • https://golang.org/pkg/go/build/ : go/build from Go Document

Refs

src/go/build/build.go 中,ctxt.BuildTags 列举了全部可用的内置的 Tags。

语法规则

https://studygolang.com/articles/19280

1)只允许是字母数字或_

2)多个条件之间,空格表示OR;逗号表示AND;叹号(!)表示NOT

3)一个文件可以有多个+build,它们之间的关系是AND。如:

1
2
3
4
// +build linux darwin
// +build 386
等价于
// +build (linux OR darwin) AND 386

4)预定义了一些条件: runtime.GOOS、runtime.GOARCH、compiler(gc或gccgo)、cgo、context.BuildTags中的其他单词

5)如果一个文件名(不含后缀),以 *_GOOS, *_GOARCH, 或 *_GOOS_GOARCH结尾,它们隐式包含了 构建约束

6)当不想编译某个文件时,可以加上// +build ignore。这里的ignore可以是其他单词,只是ignore更能让人知道什么意思

更多详细信息,可以查看go/build/build.go文件中shouldBuildmatch方法。

🔚