1. 範圍
這些實務假設使用 Go 1.27 語言語意、執行時期預設值,以及預設實驗配置。
2. 通往概念檔案的路徑
根據範圍內的程式碼和任務進行路由,專注於變更或差異中的已變更程式碼。索引結合了主題與說明性的程式碼模式。X、T、x 和 v 代表任何名稱。開啟所有匹配的參考,包括以下額外的路徑。
透過標題中的 ID 前綴尋找實務,並引用其完整 ID。遵循實務,將範例當作慣用寫法,並查閱原因、例外和權衡以了解機制、適用性和成本。訊號用於識別可能遺漏的實務。
同時開啟以下參考以尋找遺漏的防護措施或症狀:
- 模組或檔案語言版本不符、建置限制或執行時期行為覆寫:MOD。
- 檢查或忽略
error的程式碼:ERH。 - Goroutine 或通道:CTX、GOR 和 SHR。
- 阻塞 I/O(網路、資料庫、HTTP、檔案)或 HTTP 處理器:CTX。
- 並行程式碼的測試:TBA 和 TST。
- 記憶體或 goroutine 數量增長:PRO 和 MRT。
- 高 GC CPU 使用率,或容器中的程式:BRT、PRO 和 TRC。
- 熱路徑,或要求讓程式碼更快:PRO、ALO 和 BEN。
2.1 語言
- CST code-structure.md:遮蔽、套件/內建名稱(
url、len、new、max)、早期回傳(else在 return 之後)、func init()。 - STD struct-design.md:getter/setter(
GetX/SetX)、嵌入(sync.Mutex)、提升欄位字面值、函數選項(NewXWithY、Config引數)、new(expr)和指標輔助函式(ptr[T]、intPtr)。 - INT interfaces.md:介面建立/所有權、單一實作介面、具體 vs 介面回傳值、
any/interface{}、具型別 nil 介面/錯誤。 - GEN generics.md:型別參數(
[T any])、約束(comparable、~int、~string、cmp.Ordered、golang.org/x/exp/constraints)、型別推論、泛型方法、自引用約束。 - FNM functions-and-methods.md:值/指標或混合接收器、攜帶 mutex 的值接收器、具名回傳值(
n int, err error)、裸露回傳。 - LOP loops.md:range 複製(
v.field =)、表達式求值、每次迭代變數(v := v、&v、goroutine 閉包)、range n、for i := 0; i <、slices.Backward、帶標籤的 break、switch/select內的break。 - ITR iterators.md:迭代器消費/建立、
iter.Seq/iter.Seq2(包含參數)、yield、iter.Pull、Next()/Value()、回傳所有元素為切片的方法、slices.Collect。 - DEF defer-and-cleanup.md:迴圈中的
defer、延後引數/接收器求值、io.Closer清理(defer f.Close()、resp.Body、rows.Close())、Close/Sync錯誤、os.Create。
2.2 資料
- NUM numbers.md:八進位(
0644)、整數溢位(int32(、math.MaxInt)、浮點數==、NaN/Inf、math.FMA。 - SLC slices.md:長度/容量、
append別名、預先分配(make([])、nil/空([]T{}、s == nil)、len檢查、copy/slices.Clone、[low:high:max]、切片轉陣列轉換。 - COL collection-helpers.md:
min/max、slices插入/刪除/排序/搜尋、maps、cmp、clear。舊形式:sort.Slice、math.Min/math.Max、append(s[:i], s[i+1:]...)、map 清除delete迴圈。 - MAP maps.md:map 大小設定(
make(map、map[K]V{})、排序鍵(maps.Keys、sort.Strings)、map 迭代期間的寫入。 - MRT memory-retention.md:快取/長生命週期 map(map 搭配 mutex、刪除、尖峰後大小)、保留的子字串/子切片、清零已棄用指標、
strings.Clone/bytes.Clone、runtime.AddCleanup/runtime.SetFinalizer、unique.*、weak.*。 - CMP comparison.md:可比型別(介面/結構上的
==、[T comparable])、slices.Equal/maps.Equal、reflect.DeepEqual、函數值(runtime.FuncForPC)。 - STX strings-text.md:位元組/符文(將
len(s)視為字元數、[]rune)、UTF-8 驗證(utf8)、string(int)、字串 range、unicode表格。 - SPR strings-processing.md:
Trim*/Cut*、SplitSeq/FieldsSeq/Lines、strings.Split/strings.Index、strings.Builder、字串+=迴圈、bytes/bytes.Buffer、fmt.Append*/strconv.Append*、[]byte(fmt.Sprintf(。
2.3 錯誤
- PAN panics.md:
panicvserror、recover、Must、panic(nil)/panicnil、debug.SetCrashOutput。 - ERC errors-creating.md:包裝(
%w/%v、fmt.Errorf、無上下文return err/return nil, err)、errors.New、哨兵(var Err)vs 錯誤型別(Error() string)、errors.Join、ErrUnsupported。 - ERH errors-handling.md:
errors.Is/errors.AsType、err ==、err.(type)、errors.As、訊息比較、逾時/取消哨兵(net.Error、os.ErrDeadlineExceeded、context.DeadlineExceeded)、在結果之前檢查err、忽略的錯誤(_ =、x, _ :=)。 - LOG logging.md:
log/slog設定與錯誤記錄、log.Printf/log.Println、記錄並回傳相同錯誤。
2.4 並行
- CND concurrency-design.md:並行 vs 平行、生成閾值(每個元素的 goroutine)、工作者池大小、
runtime.NumCPU()、GOMAXPROCS。 - SHR shared-state.md:資料競賽、先發生關係、競爭條件、mutex vs 通道、goroutine 寫入、
sync.Mutex/RLock、鎖定下的格式化(fmt.Sprintf)、共享append/map。 - SYN sync-primitives.md:具型別原子操作(
sync/atomic、atomic.Pointer、atomic.AddInt64/atomic.Value、goroutinen++)、sync.Map、sync.Once/sync.OnceValue、sync.Cond、複製的sync值。 - GOR goroutine-lifecycle.md:goroutine 洩漏、停止計畫/擁有者、早期回傳後封鎖的傳送者、無緩衝結果通道、
go func()、sync.WaitGroup、wg.Add/wg.Go、errgroup(g.Go、SetLimit)。 - CHA channels.md:通知通道與大小設定(
make(chan、chan bool、chan struct{})、select優先順序、nil 通道、close。 - CTX context.md:傳遞
context.Context、defer cancel()/context.WithTimeout、圍繞阻塞操作的ctx.Done()、值鍵(context.WithValue、ctx.Value)、main之外的context.Background()。 - CXC context-cancellation.md:取消原因(
ctx.Err()、<-ctx.Done()、context.Canceled/context.DeadlineExceeded/context.Cause、WithCancelCause)、context.AfterFunc、背景工作(WithoutCancel、goroutiner.Context())、signal.Notify/signal.NotifyContext。
2.5 標準函式庫
- TIM time.md:
time.Duration單位/純數字、time.Time比較(==)、迴圈中的計時器(time.After)、time.NewTimer、time.Tick。 - JSN json.md:
encoding/json、encoding/json/v2、JSON 標籤(omitzero、omitempty)、嵌入的序列化器、數字解碼(json.Unmarshal到map[string]any)。 - SQL database-sql.md:
database/sql、sql.Open、PingContext、連線池大小、查詢引數/預備陳述式(db.Query、.Exec、QueryRow、ExecContext、透過fmt.Sprintf的 SQL)、sql.Null[T]、rows.Next/rows.Err。 - IOF io-and-files.md:
io.Reader/io.Writer和fs.FS參數、filename string、os.Open、os.ReadFile、os.DirFS、os.Root、使用使用者輸入的filepath.Join。 - HCL http-client-and-net.md:客戶端逾時/共享/連線池(
http.Get、http.Post、http.DefaultClient、http.Client、http.Transport)、net/netipvsnet.IP/net.ParseIP、net.JoinHostPortvsfmt.Sprintf("%s:%d"。 - HSV http-server.md:處理器(
http.ResponseWriter、*http.Request、http.Handler、r.Body/r.Method)、ServeMux模式/HandleFunc、http.Error、伺服器逾時(http.ListenAndServe、http.Server)、MaxBytesHandler、ResponseController、CrossOriginProtection。 - RND randomness-and-ids.md:
uuid、crypto/rand、math/rand、math/rand/v2、rand.Seed。
2.6 測試
- TBA testing-basics.md:測試類別/建置標籤(
func TestX、//go:build integration)、-race、t.Parallel、-shuffle、表格驅動測試/t.Run、輔助函式、外部_test套件。 - TST testing-state.md:
t.Cleanup、TestMain、t.Contextvs 測試context.Background()、t.Chdir/t.Setenv/t.TempDirvsos.Chdir/os.Setenv/os.MkdirTemp、testing/synctest、測試時間/time.Sleep、cryptotest。 - TTL testing-tools.md:
httptest、testing/iotest、fstest、slogtest、模糊測試(func FuzzX)。 - BEN benchmarks.md:
func BenchmarkX、b.Loopvsb.N/b.ResetTimer、代表性輸入/重複使用、benchstat。 - COV coverage-and-test-output.md:
-coverpkg、-cover、go build -cover/GOCOVERDIR、t.Output/t.Attr/t.ArtifactDir、測試fmt.Println、go test -json。
2.7 效能
僅在基準測試、效能剖析或追蹤已識別的熱路徑上應用佈局、分配和內聯實務。
- PRO profiling.md:pprof(
net/http/pprof、/debug/pprof、runtime/pprof、pprof.Lookup)、堆積差異、goroutine 轉儲、goroutineleak/阻塞/mutex 剖析(SetBlockProfileRate、SetMutexProfileFraction)、標籤(pprof.Do)、goroutine 計數(runtime/metrics)。 - TRC tracing.md:執行追蹤(
runtime/trace、trace.Start)、飛行記錄器(FlightRecorder)、延遲尖峰/罕見慢請求、排程/GC 暫停。 - MLY memory-layout.md:快取局部性/跨步(熱
[]*T迴圈)、虛假共享(一個切片中的每個 goroutine 計數器)、指令層級並行、欄位對齊、structs.HostLayout。 - ALO allocations.md:逃逸分析(
-gcflags、回傳區域指標)、呼叫者擁有的緩衝區、編譯器省略的轉換(熱string(b))、allocs/op、sync.Pool。 - BRT build-and-runtime-tuning.md:內聯、PGO(
default.pgo)、GOGC/GOMEMLIMIT/debug.SetGCPercent、容器感知GOMAXPROCS(automaxprocs、runtime.GOMAXPROCS)。 - CGO cgo.md:批次 cgo 呼叫(
import "C"、C.)、#cgo指令(noescape、nocallback)。
2.8 專案與工具
- PKG packages-and-docs.md:專案佈局、套件凝聚力/名稱(
util、common)、別名(type X = Y、//go:fix inline)、文件註解、遺漏的匯出文件註解、Deprecated:、範例(func ExampleX)。 - TOL tooling.md:
gofmt、go vet、linter(golangci-lint)、tool指令/tools.go、go fix現代化工具、測試 vet 檢查(-vet=)、CI 腳本、@latest。 - MOD modules-and-builds.md:
go.mod衛生/replace、godebug///go:debug、工作區(go.work)、建置限制(//go:build、// +build)。
3. 應用於任務
- 撰寫程式碼: 滿足路由檔案中所有適用的實務。
- 審查程式碼: 當指令可用時,首先執行
go vet ./...、go test -race ./...和go fix -diff ./...,如果程式碼必須保持不變,則使用副本。檢查每個路由檔案中的每個訊號項目。排除例外涵蓋的命中。將其餘部分報告為ID | file:line | what is wrong | fix。對於重疊的實務,先引用最具體的 ID,然後再引用其他 ID。對於沒有實務涵蓋的問題,使用-。按影響排序:結果錯誤、競賽、恐慌、洩漏、掛起,然後是資源/效能問題,然後是過時的慣用寫法/風格。 - 除錯: 將症狀匹配到訊號和原因,在程式碼中確認機制,然後應用實務。
- 現代化程式碼: 執行
go fix ./...直到 diff 為空以應用現代化工具,然後審查 diff。現代化工具會跳過它們無法證明安全的程式碼形狀,因此檢查路由檔案的訊號以找出剩餘的過時慣用寫法,並手動重寫。當路由檔案沒有匹配的訊號項目,且go vet ./...和測試通過時,即完成。
在聲明效能提升之前,請使用基準測試或效能剖析進行測量。