# 開發工具

本頁介紹 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 指令總覽](/start-go-command)。

### 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`：

```go
package main
import ("os";"fmt")
func main(){
names:=[]string{"go","gopher"}
for i,n:=range names{
fmt.Println(i,   n)
}
os.Exit(0)
}
```

執行：

```text
$ gofmt -l .
$ gofmt -d main.go
```

輸出：

```text
main.go
diff main.go.orig main.go
--- main.go.orig
+++ main.go
@@ -1,9 +1,14 @@
 package main
-import ("os";"fmt")
-func main(){
-names:=[]string{"go","gopher"}
-for i,n:=range names{
-fmt.Println(i,   n)
-}
-os.Exit(0)
+
+import (
+	"fmt"
+	"os"
+)
+
+func main() {
+	names := []string{"go", "gopher"}
+	for i, n := range names {
+		fmt.Println(i, n)
+	}
+	os.Exit(0)
 }
```

接著實際改寫並執行：

```text
$ go fmt ./...
$ cat main.go
$ go run .
```

輸出：

```text
main.go
package main

import (
	"fmt"
	"os"
)

func main() {
	names := []string{"go", "gopher"}
	for i, n := range names {
		fmt.Println(i, n)
	}
	os.Exit(0)
}
0 go
1 gopher
```

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

### go vet

`go vet` 會靜態檢查程式碼，找出「編譯器不擋、但幾乎一定是寫錯」的地方，例如：

- `Printf` 的格式動詞（`%s`、`%d`）和參數型別對不上
- 把含有 `sync.Mutex` 的結構體以值傳遞，複製了鎖（見 [Mutex](/sync-mutex)）
- 永遠不會執行到的程式碼、錯誤的 struct tag 等

下面的 `main.go` 能編譯、能執行，但有兩個 bug：

```go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu sync.Mutex
	n  int
}

func show(c Counter) {
	fmt.Printf("count = %d\n", c.n)
}

func main() {
	name := "gopher"
	age := 10
	fmt.Printf("%s is %d years old\n", age, name)

	var c Counter
	c.n = 3
	show(c)
}
```

執行：

```text
$ go run .
$ go vet ./...
```

輸出：

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

程式照樣跑完，只是輸出怪怪的；`go vet` 則直接指出參數順序寫反，以及 `Counter` 被複製。修正後的版本：

```go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu sync.Mutex
	n  int
}

func show(c *Counter) {
	fmt.Printf("count = %d\n", c.n)
}

func main() {
	name := "gopher"
	age := 10
	fmt.Printf("%s is %d years old\n", name, age)

	var c Counter
	c.n = 3
	show(&c)
}
```

```text
$ go vet ./...
$ go run .
```

輸出：

```text
gopher is 10 years old
count = 3
```

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

### 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` 仍會列出簽名。

查標準庫：

```text
$ go doc strings.Cut
$ go doc -short strings | grep -E '^func (Cut|Contains|Split)\('
$ go doc fmt.Stringer
```

輸出：

```text
package strings // import "strings"

func Cut(s, sep string) (before, after string, found bool)
    Cut slices s around the first instance of sep, returning the text before and
    after sep. The found result reports whether sep appears in s. If sep does
    not appear in s, cut returns s, "", false.

func Contains(s, substr string) bool
func Cut(s, sep string) (before, after string, found bool)
func Split(s, sep string) []string
package fmt // import "fmt"

type Stringer interface {
	String() string
}
    Stringer is implemented by any value that has a String method, which defines
    the “native” format for that value. The String method is used to print
    values passed as an operand to any format that accepts a string or to an
    unformatted printer such as Print.

```

查自己的套件。檔案樹：

```text
geo/
├── go.mod
├── main.go
└── shape/
    └── shape.go
```

`go.mod`：

```text
module example.com/geo

go 1.25.0
```

`shape/shape.go`：

```go
package shape

import "math"

type Circle struct {
	R float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.R * c.R
}

func NewCircle(r float64) Circle {
	return Circle{R: r}
}

func helper() {}
```

`main.go`：

```go
package main

import (
	"fmt"

	"example.com/geo/shape"
)

func main() {
	fmt.Printf("%.2f\n", shape.NewCircle(2).Area())
}
```

執行：

```text
$ go run .
$ go doc ./shape
$ go doc ./shape.Circle
$ go doc -u ./shape helper
```

輸出：

```text
12.57
package shape // import "example.com/geo/shape"

type Circle struct{ ... }
    func NewCircle(r float64) Circle
package shape // import "example.com/geo/shape"

type Circle struct {
	R float64
}

func NewCircle(r float64) Circle
func (c Circle) Area() float64
package shape // import "example.com/geo/shape"

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`：

```go
package main

import "fmt"

func main() {
	fmt.Println("app running")
}
```

加入並執行工具：

```text
$ go get -tool example.com/hellotool@v1.0.0
$ cat go.mod
$ go tool hellotool -name gopher
$ go tool
$ go run .
```

輸出：

```text
go: downloading example.com/hellotool v1.0.0
go: added example.com/hellotool v1.0.0
module example.com/app

go 1.25.0

tool example.com/hellotool

require example.com/hellotool v1.0.0 // indirect
hellotool v1.0.0, args: [-name gopher]
asm
cgo
compile
cover
fix
link
preprofile
vet
example.com/hellotool
app running
```

工具被記成 `// indirect`，因為程式碼沒有匯入它；它不會被編譯進你的程式，只在 `go tool` 時建置並快取。

移除工具：

```text
$ go mod edit -droptool=example.com/hellotool
$ go mod tidy -v
$ cat go.mod
$ go tool hellotool
```

輸出：

```text
unused example.com/hellotool
module example.com/app

go 1.25.0
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 名稱` 執行，版本全隊一致

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
