開發工具

最後更新


本頁介紹 Go 內建的四個日常開發工具:排版用的 gofmt、抓可疑程式碼的 go vet、查文件的 go doc,以及用 go.mod 的 tool 指示管理專案工具(Go 1.24 起)。

為什麼要用這些工具


Go 把「寫程式之外的雜事」盡量交給工具處理:
工具解決的問題什麼時候用
gofmt/go fmt縮排、空白、import 排序的風格爭論存檔時(編輯器通常會自動執行)
go vet能編譯、但很可能是 bug 的寫法提交程式碼前、CI 中
go doc不想離開終端機就查 API 簽名與說明寫程式時隨時
tool 指示團隊成員各自安裝的工具版本不一致專案需要程式碼產生器、linter 等工具時

go 指令其他子指令的概觀見 go 指令總覽。

gofmt 與 go fmt


gofmt 會把 Go 原始碼排成唯一的標準格式:用 tab 縮排、運算子兩側加空白、import 分組排序等。整個 Go 社群都用同一種格式,所以讀別人的程式碼不會有風格落差,也不必在 code review 時爭論排版。
常用寫法:
指令作用
gofmt -l .列出格式不符的檔案,不修改
gofmt -d 檔案印出會怎麼改(diff),不修改
gofmt -w 檔案直接改寫檔案
go fmt ./...對 module 內所有套件執行 gofmt -l -w,印出被改的檔案

下面是一個能編譯、但排版很亂的 main.go:
  1. package main
  2. import ("os";"fmt")
  3. func main(){
  4. names:=[]string{"go","gopher"}
  5. for i,n:=range names{
  6. fmt.Println(i, n)
  7. }
  8. os.Exit(0)
  9. }

執行:
  1. $ gofmt -l .
  2. $ gofmt -d main.go

輸出:
  1. main.go
  2. diff main.go.orig main.go
  3. --- main.go.orig
  4. +++ main.go
  5. @@ -1,9 +1,14 @@
  6. package main
  7. -import ("os";"fmt")
  8. -func main(){
  9. -names:=[]string{"go","gopher"}
  10. -for i,n:=range names{
  11. -fmt.Println(i, n)
  12. -}
  13. -os.Exit(0)
  14. +
  15. +import (
  16. + "fmt"
  17. + "os"
  18. +)
  19. +
  20. +func main() {
  21. + names := []string{"go", "gopher"}
  22. + for i, n := range names {
  23. + fmt.Println(i, n)
  24. + }
  25. + os.Exit(0)
  26. }

接著實際改寫並執行:
  1. $ go fmt ./...
  2. $ cat main.go
  3. $ go run .

輸出:
  1. main.go
  2. package main
  3. import (
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. names := []string{"go", "gopher"}
  9. for i, n := range names {
  10. fmt.Println(i, n)
  11. }
  12. os.Exit(0)
  13. }
  14. 0 go
  15. 1 gopher

格式化後再執行 gofmt -l . 不會印出任何東西,CI 常用這招檢查是否有人忘了排版。

go vet


go vet 會靜態檢查程式碼,找出「編譯器不擋、但幾乎一定是寫錯」的地方,例如:
  • Printf 的格式動詞(%s、%d)和參數型別對不上
  • 把含有 sync.Mutex 的結構體以值傳遞,複製了鎖(見 Mutex)
  • 永遠不會執行到的程式碼、錯誤的 struct tag 等

下面的 main.go 能編譯、能執行,但有兩個 bug:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Counter struct {
  7. mu sync.Mutex
  8. n int
  9. }
  10. func show(c Counter) {
  11. fmt.Printf("count = %d\n", c.n)
  12. }
  13. func main() {
  14. name := "gopher"
  15. age := 10
  16. fmt.Printf("%s is %d years old\n", age, name)
  17. var c Counter
  18. c.n = 3
  19. show(c)
  20. }

執行:
  1. $ go run .
  2. $ go vet ./...

輸出:
  1. %!s(int=10) is %!d(string=gopher) years old
  2. count = 3
  3. main.go:13:13: show passes lock by value: example.com/vetdemo.Counter contains sync.Mutex
  4. main.go:24:7: call of show copies lock value: example.com/vetdemo.Counter contains sync.Mutex
  5. main.go:20:14: fmt.Printf format %s has arg age of wrong type int

程式照樣跑完,只是輸出怪怪的;go vet 則直接指出參數順序寫反,以及 Counter 被複製。修正後的版本:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Counter struct {
  7. mu sync.Mutex
  8. n int
  9. }
  10. func show(c *Counter) {
  11. fmt.Printf("count = %d\n", c.n)
  12. }
  13. func main() {
  14. name := "gopher"
  15. age := 10
  16. fmt.Printf("%s is %d years old\n", name, age)
  17. var c Counter
  18. c.n = 3
  19. show(&c)
  20. }

  1. $ go vet ./...
  2. $ go run .

輸出:
  1. gopher is 10 years old
  2. count = 3

go vet 沒發現問題時不印任何東西,結束碼為 0;有問題時結束碼非 0,適合放進 CI。另外,go test 會自動執行一小部分高可信度的 vet 檢查(見單元測試)。

go doc


go doc 在終端機顯示套件、函式、型別的簽名與說明文件,不需要開瀏覽器:
指令顯示
go doc strings套件說明與匯出名稱清單
go doc strings.Cut單一函式
go doc -short strings每個匯出名稱一行
go doc ./shape自己專案裡的套件
go doc -u ./shape helper連未匯出(小寫開頭)的名稱也顯示

說明文字來自宣告正上方、緊貼著的註解(doc comment);沒有寫說明時,go doc 仍會列出簽名。
查標準庫:
  1. $ go doc strings.Cut
  2. $ go doc -short strings | grep -E '^func (Cut|Contains|Split)\('
  3. $ go doc fmt.Stringer

輸出:
  1. package strings // import "strings"
  2. func Cut(s, sep string) (before, after string, found bool)
  3. Cut slices s around the first instance of sep, returning the text before and
  4. after sep. The found result reports whether sep appears in s. If sep does
  5. not appear in s, cut returns s, "", false.
  6. func Contains(s, substr string) bool
  7. func Cut(s, sep string) (before, after string, found bool)
  8. func Split(s, sep string) []string
  9. package fmt // import "fmt"
  10. type Stringer interface {
  11. String() string
  12. }
  13. Stringer is implemented by any value that has a String method, which defines
  14. the “native” format for that value. The String method is used to print
  15. values passed as an operand to any format that accepts a string or to an
  16. unformatted printer such as Print.

查自己的套件。檔案樹:
  1. geo/
  2. ├── go.mod
  3. ├── main.go
  4. └── shape/
  5. └── shape.go

go.mod:
  1. module example.com/geo
  2. go 1.25.0

shape/shape.go:
  1. package shape
  2. import "math"
  3. type Circle struct {
  4. R float64
  5. }
  6. func (c Circle) Area() float64 {
  7. return math.Pi * c.R * c.R
  8. }
  9. func NewCircle(r float64) Circle {
  10. return Circle{R: r}
  11. }
  12. func helper() {}

main.go:
  1. package main
  2. import (
  3. "fmt"
  4. "example.com/geo/shape"
  5. )
  6. func main() {
  7. fmt.Printf("%.2f\n", shape.NewCircle(2).Area())
  8. }

執行:
  1. $ go run .
  2. $ go doc ./shape
  3. $ go doc ./shape.Circle
  4. $ go doc -u ./shape helper

輸出:
  1. 12.57
  2. package shape // import "example.com/geo/shape"
  3. type Circle struct{ ... }
  4. func NewCircle(r float64) Circle
  5. package shape // import "example.com/geo/shape"
  6. type Circle struct {
  7. R float64
  8. }
  9. func NewCircle(r float64) Circle
  10. func (c Circle) Area() float64
  11. package shape // import "example.com/geo/shape"
  12. func helper()

go doc 會把回傳 Circle 的建構函式 NewCircle 歸在 Circle 底下;helper 是未匯出名稱,預設不顯示,要加 -u。

go.mod 的 tool 指示


專案常需要額外的命令列工具,例如程式碼產生器或 linter。以前大家各自 go install,版本容易不一致。Go 1.24 起,可以把工具登記在 go.mod 的 tool 指示中,版本和其他依賴一樣由 go.mod、go.sum 鎖定,所有人執行的都是同一版。
指令作用
go get -tool 路徑@版本加入工具(寫入 tool 與 require)
go tool 名稱 [參數]執行工具,名稱是匯入路徑的最後一段
go tool列出內建工具與 go.mod 登記的工具
go get tool把所有登記的工具升級到最新版
go mod edit -droptool=路徑移除 tool 指示,之後 go mod tidy 清掉 require

本節的 example.com/hellotool 是放在本機模擬 module proxy 上的示範工具,它只會印出收到的參數。
main.go:
  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("app running")
  5. }

加入並執行工具:
  1. $ go get -tool example.com/hellotool@v1.0.0
  2. $ cat go.mod
  3. $ go tool hellotool -name gopher
  4. $ go tool
  5. $ go run .

輸出:
  1. go: downloading example.com/hellotool v1.0.0
  2. go: added example.com/hellotool v1.0.0
  3. module example.com/app
  4. go 1.25.0
  5. tool example.com/hellotool
  6. require example.com/hellotool v1.0.0 // indirect
  7. hellotool v1.0.0, args: [-name gopher]
  8. asm
  9. cgo
  10. compile
  11. cover
  12. fix
  13. link
  14. preprofile
  15. vet
  16. example.com/hellotool
  17. app running

工具被記成 // indirect,因為程式碼沒有匯入它;它不會被編譯進你的程式,只在 go tool 時建置並快取。
移除工具:
  1. $ go mod edit -droptool=example.com/hellotool
  2. $ go mod tidy -v
  3. $ cat go.mod
  4. $ go tool hellotool

輸出:
  1. unused example.com/hellotool
  2. module example.com/app
  3. go 1.25.0
  4. go: no such tool "hellotool"

注意:工具的依賴也會出現在你的 go.mod 中,並參與版本選擇;工具依賴很多套件時,可能把你程式用到的共同依賴版本往上拉。

重點整理


  • gofmt/go fmt 把程式碼排成社群唯一標準格式,gofmt -l 可在 CI 檢查
  • go vet 找出能編譯但很可能是 bug 的寫法,例如 Printf 參數錯誤、複製鎖
  • go doc 套件.名稱 在終端機查簽名與說明,-u 顯示未匯出名稱
  • Go 1.24 起用 go get -tool 把工具登記在 go.mod,以 go tool 名稱 執行,版本全隊一致

資料來源