writing-go
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGo Development (1.25+)
Go开发(1.25+)
Core Principles
核心原则
- Stdlib first: External deps only when justified
- Concrete types: Define interfaces at consumer, return structs
- Composition: Over inheritance, always
- Fail fast: Clear errors with context
- Simple: The obvious solution is usually correct
- 优先使用标准库:仅在合理情况下引入外部依赖
- 具体类型:在消费端定义接口,返回结构体
- 优先组合:始终采用组合而非继承
- 快速失败:提供带上下文的清晰错误信息
- 简洁性:显而易见的方案通常是正确的
Quick Patterns
常用模式
Error Handling
错误处理
go
if err := doThing(); err != nil {
return fmt.Errorf("do thing: %w", err)
}go
if err := doThing(); err != nil {
return fmt.Errorf("do thing: %w", err)
}Struct with Options
带选项的结构体
go
type Server struct {
addr string
timeout time.Duration
}
func NewServer(addr string, opts ...Option) *Server {
s := &Server{addr: addr, timeout: 30 * time.Second}
for _, opt := range opts {
opt(s)
}
return s
}go
type Server struct {
addr string
timeout time.Duration
}
func NewServer(addr string, opts ...Option) *Server {
s := &Server{addr: addr, timeout: 30 * time.Second}
for _, opt := range opts {
opt(s)
}
return s
}Table-Driven Tests
表驱动测试
go
tests := []struct {
name string
input string
want string
wantErr bool
}{
{"valid", "hello", "HELLO", false},
{"empty", "", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Process(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}go
tests := []struct {
name string
input string
want string
wantErr bool
}{
{"valid", "hello", "HELLO", false},
{"empty", "", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Process(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}Go 1.25 Features
Go 1.25新特性
- testing/synctest: Deterministic concurrent testing with simulated clock
- encoding/json/v2: Experimental, 3-10x faster (GOEXPERIMENT=jsonv2)
- runtime/trace.FlightRecorder: Production trace capture on-demand
- Container-aware GOMAXPROCS: Auto-detects cgroup limits
- GreenTea GC: Experimental, lower latency (GOEXPERIMENT=greenteagc)
- testing/synctest:基于模拟时钟的确定性并发测试
- encoding/json/v2:实验性版本,速度提升3-10倍(需设置GOEXPERIMENT=jsonv2)
- runtime/trace.FlightRecorder:支持生产环境按需捕获追踪数据
- 容器感知的GOMAXPROCS:自动检测cgroup限制
- GreenTea GC:实验性垃圾回收器,延迟更低(需设置GOEXPERIMENT=greenteagc)
References
参考资料
- PATTERNS.md - Detailed code patterns
- TESTING.md - Testing strategies with testify/mockery
- CLI.md - CLI application patterns
- PATTERNS.md - 详细代码模式文档
- TESTING.md - 结合testify/mockery的测试策略
- CLI.md - CLI应用开发模式
Tooling
工具链
bash
go build ./... # Build
go test -race ./... # Test with race detector
golangci-lint run # Lint
mockery --all # Generate mocksbash
go build ./... # 编译所有包
go test -race ./... # 启用竞争检测器进行测试
golangci-lint run # 代码静态检查
mockery --all # 生成模拟对象