go

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go

Go

Workflow

工作流程

  1. Confirm Go version, module layout, and package boundaries (
    go env
    ,
    go list
    ,
    go mod tidy
    when appropriate).
  2. Apply idiomatic Go style and naming (gofmt/goimports, no stutter, small packages).
  3. Handle errors explicitly and consistently (wrapping,
    errors.Is/As
    , no panic for expected errors).
  4. Validate context usage, cancellation/timeouts, and resource cleanup (files, HTTP bodies, goroutines).
  5. Review concurrency for races, leaks, and lifecycle management.
  6. Add/update tests and validate with
    go test
    ,
    go vet
    , and
    -race
    when relevant.
  1. 确认Go版本、模块布局和包边界(必要时使用
    go env
    go list
    go mod tidy
    )。
  2. 遵循Go语言的惯用风格和命名规范(使用gofmt/goimports,避免命名重复,保持包体积小巧)。
  3. 显式且一致地处理错误(错误包装、
    errors.Is/As
    ,预期错误场景不使用panic)。
  4. 验证context的使用、取消/超时机制以及资源清理(文件、HTTP请求体、goroutine)。
  5. 审查并发逻辑,检查竞态条件、goroutine泄漏和生命周期管理。
  6. 添加/更新测试,使用
    go test
    go vet
    ,相关场景下使用
    -race
    选项验证。

Preflight (Ask / Check First)

前置检查(先询问/确认)

  • Target Go version (from
    go.mod
    and CI).
  • Confirm
    go
    /
    toolchain
    directives are intentional for reproducible builds across dev and CI.
  • 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版本(来自
    go.mod
    和CI配置)。
  • 确认
    go
    /
    toolchain
    指令是为了在开发和CI环境中实现可复现构建而有意设置的。
  • 包边界和公共API范围(导出的标识符)。
  • 当前代码是库代码还是服务代码(日志、配置、主程序)。
  • 并发模型:每个请求对应一个goroutine?后台工作线程?是否支持取消?

Project Structure

项目结构

  • Use
    go.mod
    and keep modules small and focused.
  • Organize packages by domain, not by type.
  • Avoid circular dependencies and overly deep package trees.
  • Use
    internal/
    for packages that should not be imported externally.
  • Use
    cmd/<name>/
    for multiple binaries when applicable.
  • 使用
    go.mod
    ,保持模块小巧且聚焦单一功能。
  • 按业务领域组织包,而非按类型划分。
  • 避免循环依赖和过深的包层级。
  • 对于不应被外部导入的包,使用
    internal/
    目录。
  • 多二进制文件场景下,使用
    cmd/<name>/
    目录结构。

Naming and Style

命名与风格

  • Use concise, descriptive names; avoid stutter (
    package user
    ,
    type User
    ).
  • Favor small, focused functions.
  • Use
    gofmt
    and
    goimports
    consistently.
  • Avoid
    GetX()
    ; prefer
    X()
    for getters.
  • Preserve initialisms (
    ID
    ,
    HTTP
    ,
    URL
    ) in exported names.
  • 使用简洁、具有描述性的名称;避免命名重复(如
    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
    errors.Is
    and
    errors.As
    for inspection.
  • Keep error strings lowercase and without trailing punctuation.
  • 显式返回错误;正常流程中避免使用panic。
  • 必要时为错误添加上下文信息并使用哨兵错误。
  • 优先使用
    errors.Is
    errors.As
    检查错误类型。
  • 错误字符串使用小写,且不添加结尾标点。

Context and Cancellation

Context与取消机制

  • Pass
    context.Context
    as the first param when needed.
  • 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
    sync.WaitGroup
    for lifecycle coordination.
  • Run
    go test -race
    for concurrent code and treat races as correctness bugs.
  • Ensure goroutines have an exit condition to avoid leaks.
  • 避免共享可变状态;合理使用通道或互斥锁。
  • 仅由发送方关闭通道;避免从多个goroutine关闭同一通道。
  • 使用
    sync.WaitGroup
    协调goroutine生命周期。
  • 针对并发代码运行
    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
    bytes.Buffer
    and preallocate slices.
  • Benchmark before optimizing; use
    pprof
    when needed.
  • 避免不必要的内存分配;使用
    bytes.Buffer
    并预分配切片。
  • 优化前先进行基准测试;必要时使用
    pprof
    分析性能。

Testing

测试

  • Table-driven tests for coverage and clarity.
  • Use subtests (
    t.Run
    ) and helpers for shared setup.
  • Prefer integration tests for real-world flows.
  • Add regression tests for bug fixes.
  • 使用表驱动测试提升覆盖率和可读性。
  • 使用子测试(
    t.Run
    )和辅助函数处理共享初始化逻辑。
  • 优先使用集成测试验证真实业务流程。
  • 为Bug修复添加回归测试。

Tooling

工具链

  • Run
    gofmt
    /
    goimports
    on changed files.
  • Run
    go test ./...
    and
    go test -race ./...
    when concurrency is involved.
  • Run
    go vet ./...
    and a linter suite (e.g., golangci-lint/staticcheck) when configured.
  • Keep CI on supported Go release lines (current and previous major per Go release policy).
  • When bumping
    go
    or
    toolchain
    via
    go get go@...
    , run
    go mod tidy
    to normalize module metadata.
Common commands:
bash
gofmt -w .
goimports -w .
go test ./...
go test -race ./...
go vet ./...
go mod tidy
  • 对修改的文件运行
    gofmt
    /
    goimports
  • 涉及并发逻辑时,运行
    go test ./...
    go test -race ./...
  • 运行
    go vet ./...
    ,配置完成后使用静态检查套件(如golangci-lint/staticcheck)。
  • 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 tidy

Review 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
    internal/
    for non-public packages.
  • 保持包小巧且目标明确。
  • 通过将共享类型移至底层包避免循环依赖。
  • 非公共包优先使用
    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
    go test ./...
    to CI with race detector when possible.
  • Run
    golangci-lint
    with a minimal, agreed set of linters.
  • 针对可重复场景使用表驱动测试。
  • CI中添加
    go test ./...
    ,可能的话启用竞态检测器。
  • 使用
    golangci-lint
    ,配置一组经过共识的最小化检查规则。

Reference Index

参考索引

  • rg -n "Error handling|wrap" references/go-best-practices.md
  • rg -n "Concurrency|goroutines|channels" references/go-best-practices.md
  • rg -n "Testing|table-driven" references/go-best-practices.md
  • rg -n "Error handling|wrap" references/go-best-practices.md
  • rg -n "Concurrency|goroutines|channels" references/go-best-practices.md
  • rg -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.md
  • rg -n "Example|examples" references/go-best-practices.md
  • rg -n "Workflow|process" references/go-best-practices.md
  • rg -n "Pitfall|anti-pattern" references/go-best-practices.md
  • rg -n "Testing|validation" references/go-best-practices.md
  • rg -n "Security|risk" references/go-best-practices.md
  • rg -n "Configuration|config" references/go-best-practices.md
  • rg -n "Deployment|operations" references/go-best-practices.md
  • rg -n "Troubleshoot|debug" references/go-best-practices.md
  • rg -n "Performance|latency" references/go-best-practices.md
  • rg -n "Reliability|availability" references/go-best-practices.md
  • rg -n "Monitoring|metrics" references/go-best-practices.md
  • rg -n "Error|failure" references/go-best-practices.md
  • rg -n "Decision|tradeoff" references/go-best-practices.md
  • rg -n "Migration|upgrade" references/go-best-practices.md
  • rg -n "Checklist|checklist" references/go-best-practices.md
  • rg -n "Example|examples" references/go-best-practices.md
  • rg -n "Workflow|process" references/go-best-practices.md
  • rg -n "Pitfall|anti-pattern" references/go-best-practices.md
  • rg -n "Testing|validation" references/go-best-practices.md
  • rg -n "Security|risk" references/go-best-practices.md
  • rg -n "Configuration|config" references/go-best-practices.md
  • rg -n "Deployment|operations" references/go-best-practices.md
  • rg -n "Troubleshoot|debug" references/go-best-practices.md
  • rg -n "Performance|latency" references/go-best-practices.md
  • rg -n "Reliability|availability" references/go-best-practices.md
  • rg -n "Monitoring|metrics" references/go-best-practices.md
  • rg -n "Error|failure" references/go-best-practices.md
  • rg -n "Decision|tradeoff" references/go-best-practices.md
  • rg -n "Migration|upgrade" references/go-best-practices.md