go vet 是 Go 語言官方提供的靜態分析工具,用於檢測 Go 程式碼中可能存在的問題和錯誤。它可以找出編譯器無法檢測到的潛在問題,例如:格式化字串錯誤、不可到達的程式碼、錯誤的並發使用等。
go vet 的主要功能(Main Features)
靜態程式碼分析(Static Code Analysis)
在編譯前檢測潛在問題
提供程式碼品質保證
多種檢查器(Multiple Checkers)
內建多種檢查規則
可以自定義檢查項目
整合開發流程(Development Integration)
可以整合到 CI/CD 流程
支援 IDE 整合
基本用法(Basic Usage)
檢查單個檔案
1 2 3 4 5 6 7 8
# 檢查單個 Go 檔案 go vet main.go
# 檢查指定目錄下的所有 Go 檔案 go vet ./...
# 檢查當前包 go vet .
常見檢查項目
1. Printf 格式化錯誤
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package main
import"fmt"
funcmain() { name := "John" age := 25 // 錯誤:格式化動詞與參數類型不匹配 fmt.Printf("%d years old\n", name) // go vet 會檢測到這個錯誤 // 正確的寫法 fmt.Printf("%s is %d years old\n", name, age) }
2. 不可到達的程式碼
1 2 3 4 5 6 7 8 9
package main
import"fmt"
funcunreachableCode() { fmt.Println("This will be printed") return fmt.Println("This is unreachable code") // go vet 會檢測到這個問題 }
type User struct { Name string`json:"name,omitempty"` Age int`json:"age,omitempty"` // 錯誤:struct tag 格式錯誤 Email string`json:"email,omitempty" xml:"email"`// 缺少空格 }
// 正確的寫法 type UserCorrect struct { Name string`json:"name,omitempty"` Age int`json:"age,omitempty"` Email string`json:"email,omitempty" xml:"email"` }
4. 錯誤的原子操作使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package main
import ( "sync/atomic" )
type Counter struct { value int64 }
func(c *Counter) wrongIncrement() { // 錯誤:應該傳遞指標而不是值 atomic.AddInt64(c.value, 1) // go vet 會檢測到這個錯誤 }