Loading...
Loading...
Compare original and translation side by side
fmt.Errorf("operation failed: %w", err)var ErrNotFound = errors.New("not found")// Good
if err != nil {
return fmt.Errorf("failed to process user %s: %w", userID, err)
}
// Avoid
if err != nil {
log.Fatal(err) // Don't panic on recoverable errors
}fmt.Errorf("操作失败: %w", err)var ErrNotFound = errors.New("not found")// 推荐写法
if err != nil {
return fmt.Errorf("处理用户%s失败: %w", userID, err)
}
// 不推荐写法
if err != nil {
log.Fatal(err) // 不要在可恢复错误时panic
}// Good - interface defined by consumer
type Reader interface {
Read(p []byte) (n int, err error)
}
func ProcessData(r Reader) error { ... }
// Avoid - exporting implementation details
type Service interface {
Method1() error
Method2() error
Method3() error // Too many methods
}// 推荐写法 - 接口由使用者定义
type Reader interface {
Read(p []byte) (n int, err error)
}
func ProcessData(r Reader) error { ... }
// 不推荐写法 - 暴露实现细节
type Service interface {
Method1() error
Method2() error
Method3() error // 方法过多
}// Good - using errgroup
g, ctx := errgroup.WithContext(ctx)
for _, item := range items {
item := item // capture loop variable
g.Go(func() error {
return process(ctx, item)
})
}
if err := g.Wait(); err != nil {
return err
}// 推荐写法 - 使用errgroup
g, ctx := errgroup.WithContext(ctx)
for _, item := range items {
item := item // 捕获循环变量
g.Go(func() error {
return process(ctx, item)
})
}
if err := g.Wait(); err != nil {
return err
}func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive numbers", 2, 3, 5},
{"with zero", 5, 0, 5},
{"negative numbers", -2, -3, -5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := Add(tt.a, tt.b)
if got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"正数相加", 2, 3, 5},
{"含零相加", 5, 0, 5},
{"负数相加", -2, -3, -5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := Add(tt.a, tt.b)
if got != tt.want {
t.Errorf("Add(%d, %d) = %d, 预期值为 %d", tt.a, tt.b, got, tt.want)
}
})
}
}useruserServiceuseruserServiceURLHTTPIDierrReadConfigRCURLHTTPIDierrReadConfigRCinterface{}anyuser.UserServiceuser.Serviceinterface{}anyuser.UserServiceuser.Servicego vetstaticcheckgo vetstaticcheck