go
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGo
Go
Workflow
工作流程
- Confirm Go version, module layout, and package boundaries (,
go env,go listwhen appropriate).go mod tidy - Apply idiomatic Go style and naming (gofmt/goimports, no stutter, small packages).
- Handle errors explicitly and consistently (wrapping, , no panic for expected errors).
errors.Is/As - Validate context usage, cancellation/timeouts, and resource cleanup (files, HTTP bodies, goroutines).
- Review concurrency for races, leaks, and lifecycle management.
- Add/update tests and validate with ,
go test, andgo vetwhen relevant.-race
- 确认Go版本、模块布局和包边界(必要时使用、
go env、go list)。go mod tidy - 遵循Go语言的惯用风格和命名规范(使用gofmt/goimports,避免命名重复,保持包体积小巧)。
- 显式且一致地处理错误(错误包装、,预期错误场景不使用panic)。
errors.Is/As - 验证context的使用、取消/超时机制以及资源清理(文件、HTTP请求体、goroutine)。
- 审查并发逻辑,检查竞态条件、goroutine泄漏和生命周期管理。
- 添加/更新测试,使用、
go test,相关场景下使用go vet选项验证。-race
Preflight (Ask / Check First)
前置检查(先询问/确认)
- Target Go version (from and CI).
go.mod - Confirm /
godirectives are intentional for reproducible builds across dev and CI.toolchain - Package boundaries and public API surface (exported identifiers).
- Whether this is library code vs service code (logging, config, main).
- Concurrency model: goroutines per request? background workers? cancellation?
- 目标Go版本(来自和CI配置)。
go.mod - 确认/
go指令是为了在开发和CI环境中实现可复现构建而有意设置的。toolchain - 包边界和公共API范围(导出的标识符)。
- 当前代码是库代码还是服务代码(日志、配置、主程序)。
- 并发模型:每个请求对应一个goroutine?后台工作线程?是否支持取消?
Project Structure
项目结构
- Use and keep modules small and focused.
go.mod - Organize packages by domain, not by type.
- Avoid circular dependencies and overly deep package trees.
- Use for packages that should not be imported externally.
internal/ - Use for multiple binaries when applicable.
cmd/<name>/
- 使用,保持模块小巧且聚焦单一功能。
go.mod - 按业务领域组织包,而非按类型划分。
- 避免循环依赖和过深的包层级。
- 对于不应被外部导入的包,使用目录。
internal/ - 多二进制文件场景下,使用目录结构。
cmd/<name>/
Naming and Style
命名与风格
- Use concise, descriptive names; avoid stutter (,
package user).type User - Favor small, focused functions.
- Use and
gofmtconsistently.goimports - Avoid ; prefer
GetX()for getters.X() - Preserve initialisms (,
ID,HTTP) in exported names.URL
- 使用简洁、具有描述性的名称;避免命名重复(如搭配
package user)。type User - 优先编写小巧、聚焦单一职责的函数。
- 始终使用和
gofmt格式化代码。goimports - 避免使用;获取类方法优先使用
GetX()。X() - 导出名称中保留首字母缩写(如、
ID、HTTP)。URL
Error Handling
错误处理
- Return errors explicitly; avoid panics in normal flows.
- Wrap errors with context and sentinel errors where appropriate.
- Prefer and
errors.Isfor inspection.errors.As - Keep error strings lowercase and without trailing punctuation.
- 显式返回错误;正常流程中避免使用panic。
- 必要时为错误添加上下文信息并使用哨兵错误。
- 优先使用和
errors.Is检查错误类型。errors.As - 错误字符串使用小写,且不添加结尾标点。
Context and Cancellation
Context与取消机制
- Pass as the first param when needed.
context.Context - Respect cancellation and timeouts in I/O and goroutines.
- Avoid storing context in structs.
- In servers, set timeouts (HTTP clients and servers) to avoid hanging requests.
- 需要时将作为函数的第一个参数。
context.Context - 在I/O操作和goroutine中遵守取消和超时机制。
- 避免将context存储在结构体中。
- 服务端设置超时(HTTP客户端和服务端),避免请求挂起。
Concurrency
并发编程
- Avoid shared mutable state; use channels or mutexes appropriately.
- Close channels only by senders; avoid closing from multiple goroutines.
- Use for lifecycle coordination.
sync.WaitGroup - Run for concurrent code and treat races as correctness bugs.
go test -race - Ensure goroutines have an exit condition to avoid leaks.
- 避免共享可变状态;合理使用通道或互斥锁。
- 仅由发送方关闭通道;避免从多个goroutine关闭同一通道。
- 使用协调goroutine生命周期。
sync.WaitGroup - 针对并发代码运行,将竞态条件视为正确性问题。
go test -race - 确保goroutine有退出条件,避免泄漏。
Interfaces and Abstractions
接口与抽象
- Keep interfaces small and consumer-driven.
- Prefer concrete types; introduce interfaces at call sites for testing.
- Avoid "utility" mega-packages; keep abstractions close to where they are used.
- 保持接口小巧,以消费者需求为导向。
- 优先使用具体类型;仅在测试场景的调用处引入接口。
- 避免创建“工具类”大包;抽象逻辑应靠近其使用场景。
Performance
性能优化
- Avoid unnecessary allocations; use and preallocate slices.
bytes.Buffer - Benchmark before optimizing; use when needed.
pprof
- 避免不必要的内存分配;使用并预分配切片。
bytes.Buffer - 优化前先进行基准测试;必要时使用分析性能。
pprof
Testing
测试
- Table-driven tests for coverage and clarity.
- Use subtests () and helpers for shared setup.
t.Run - Prefer integration tests for real-world flows.
- Add regression tests for bug fixes.
- 使用表驱动测试提升覆盖率和可读性。
- 使用子测试()和辅助函数处理共享初始化逻辑。
t.Run - 优先使用集成测试验证真实业务流程。
- 为Bug修复添加回归测试。
Tooling
工具链
- Run /
gofmton changed files.goimports - Run and
go test ./...when concurrency is involved.go test -race ./... - Run and a linter suite (e.g., golangci-lint/staticcheck) when configured.
go vet ./... - Keep CI on supported Go release lines (current and previous major per Go release policy).
- When bumping or
goviatoolchain, rungo get go@...to normalize module metadata.go mod tidy
Common commands:
bash
gofmt -w .
goimports -w .
go test ./...
go test -race ./...
go vet ./...
go mod tidy- 对修改的文件运行/
gofmt。goimports - 涉及并发逻辑时,运行和
go test ./...。go test -race ./... - 运行,配置完成后使用静态检查套件(如golangci-lint/staticcheck)。
go vet ./... - CI环境使用Go官方支持的版本线(根据Go发布政策,使用当前和上一个主要版本)。
- 通过升级
go get go@...或go时,运行toolchain标准化模块元数据。go mod tidy
常用命令:
bash
gofmt -w .
goimports -w .
go test ./...
go test -race ./...
go vet ./...
go mod tidyReview Checklist
审查检查清单
- Code is gofmt/goimports clean and idiomatic.
- Errors are handled with context.
- Concurrency is safe and cancellable.
- Tests cover critical paths.
- No leaked goroutines or unbounded resource use.
- 代码已通过gofmt/goimports格式化,符合Go惯用风格。
- 错误处理添加了上下文信息。
- 并发逻辑安全且支持取消。
- 测试覆盖了关键路径。
- 无goroutine泄漏或无限制的资源占用。
References
参考资料
references/go-best-practices.md
references/go-best-practices.md
Extended Guidance
扩展指南
Use this for larger Go services or when concurrency is involved.
适用于大型Go服务或涉及复杂并发逻辑的场景。
Project Structure Checklist
项目结构检查清单
- Keep packages small and purpose-driven.
- Avoid cyclic imports by pushing shared types to a lower layer.
- Prefer for non-public packages.
internal/
- 保持包小巧且目标明确。
- 通过将共享类型移至底层包避免循环依赖。
- 非公共包优先使用目录。
internal/
Error Handling Rules
错误处理规则
- Wrap errors with context at boundaries.
- Avoid panic in normal error paths.
- Use sentinel errors sparingly; prefer typed errors when needed.
- 在边界处为错误添加上下文信息。
- 正常错误路径中避免使用panic。
- 谨慎使用哨兵错误;必要时优先使用类型化错误。
Concurrency Rules
并发规则
- Use contexts for cancellation and deadlines.
- Limit goroutine fan-out; use worker pools for large workloads.
- Avoid sharing mutable state without clear locking.
- 使用context实现取消和截止时间控制。
- 限制goroutine的扩散;大工作量场景使用工作池。
- 无明确锁机制时避免共享可变状态。
Testing and Tooling
测试与工具链
- Use table-driven tests for repeatable cases.
- Add to CI with race detector when possible.
go test ./... - Run with a minimal, agreed set of linters.
golangci-lint
- 针对可重复场景使用表驱动测试。
- CI中添加,可能的话启用竞态检测器。
go test ./... - 使用,配置一组经过共识的最小化检查规则。
golangci-lint
Reference Index
参考索引
rg -n "Error handling|wrap" references/go-best-practices.mdrg -n "Concurrency|goroutines|channels" references/go-best-practices.mdrg -n "Testing|table-driven" references/go-best-practices.md
rg -n "Error handling|wrap" references/go-best-practices.mdrg -n "Concurrency|goroutines|channels" references/go-best-practices.mdrg -n "Testing|table-driven" references/go-best-practices.md
API Design Notes
API设计注意事项
- Prefer small interfaces; keep implementations internal.
- Return concrete types from constructors when possible.
- Avoid exposing struct fields unless stable.
- 优先使用小巧的接口;实现逻辑保持内部可见。
- 构造函数优先返回具体类型。
- 除非字段稳定,否则避免暴露结构体字段。
Reference Index (Expanded)
扩展参考索引
rg -n "Project layout|packages" references/go-best-practices.md
rg -n "Project layout|packages" references/go-best-practices.md
Quick Questions (When Stuck)
疑难问题快速排查(卡顿时思考)
- What is the minimal change that solves the issue?
- What is the rollback plan?
- What is the highest-risk assumption?
- What is the simplest validation step?
- What is the known-good baseline?
- What evidence would change the decision?
- What is the user-visible impact?
- What is the operational impact?
- What is the most likely failure mode?
- What is the fastest safe experiment?
- 解决当前问题的最小改动是什么?
- 回滚方案是什么?
- 风险最高的假设是什么?
- 最简单的验证步骤是什么?
- 已知的可靠基线是什么?
- 哪些证据会改变当前决策?
- 对用户可见的影响是什么?
- 对运维的影响是什么?
- 最可能的故障模式是什么?
- 最快的安全实验方案是什么?
Reference Index (Extra)
额外参考索引
rg -n "Checklist|checklist" references/go-best-practices.mdrg -n "Example|examples" references/go-best-practices.mdrg -n "Workflow|process" references/go-best-practices.mdrg -n "Pitfall|anti-pattern" references/go-best-practices.mdrg -n "Testing|validation" references/go-best-practices.mdrg -n "Security|risk" references/go-best-practices.mdrg -n "Configuration|config" references/go-best-practices.mdrg -n "Deployment|operations" references/go-best-practices.mdrg -n "Troubleshoot|debug" references/go-best-practices.mdrg -n "Performance|latency" references/go-best-practices.mdrg -n "Reliability|availability" references/go-best-practices.mdrg -n "Monitoring|metrics" references/go-best-practices.mdrg -n "Error|failure" references/go-best-practices.mdrg -n "Decision|tradeoff" references/go-best-practices.mdrg -n "Migration|upgrade" references/go-best-practices.md
rg -n "Checklist|checklist" references/go-best-practices.mdrg -n "Example|examples" references/go-best-practices.mdrg -n "Workflow|process" references/go-best-practices.mdrg -n "Pitfall|anti-pattern" references/go-best-practices.mdrg -n "Testing|validation" references/go-best-practices.mdrg -n "Security|risk" references/go-best-practices.mdrg -n "Configuration|config" references/go-best-practices.mdrg -n "Deployment|operations" references/go-best-practices.mdrg -n "Troubleshoot|debug" references/go-best-practices.mdrg -n "Performance|latency" references/go-best-practices.mdrg -n "Reliability|availability" references/go-best-practices.mdrg -n "Monitoring|metrics" references/go-best-practices.mdrg -n "Error|failure" references/go-best-practices.mdrg -n "Decision|tradeoff" references/go-best-practices.mdrg -n "Migration|upgrade" references/go-best-practices.md