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: 值/指针或混合接收器、持有互斥锁的值接收器、命名返回值 (
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、删除、峰值后的大小)、保留的子串/子切片、清零丢弃的指针、
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: 数据竞态、happens-before 关系、竞态条件、互斥锁 vs 通道、goroutine 写入、
sync.Mutex/RLock、锁内格式化 (fmt.Sprintf)、共享的append/maps。 - 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)、嵌入的 marshaller、数字解码(将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/阻塞/互斥锁性能分析 (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 | 什么是错误的 | 修复。对于重叠的实践,首先引用最具体的 ID,然后是其他 ID。对于没有实践覆盖的问题,使用-。按影响排序:错误结果、竞态条件、panic、泄漏、挂起,然后是资源/性能问题,最后是过时的惯用写法/风格。 - 调试: 将症状与信号和为什么匹配,在代码中确认机制,然后应用实践。
- 现代化代码: 运行
go fix ./...直到差异为空以应用现代化器,然后审查差异。现代化器会跳过无法证明安全的代码形状,因此检查已定位文件的信号以查找剩余的过时惯用写法,并手动重写。当已定位文件的信号要点都不匹配,且go vet ./...和测试通过时,现代化完成。
在声称性能提升之前,请使用基准测试或性能分析进行测量。