golang

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Development

Go开发

Write clean, concurrent, idiomatic Go code.
编写简洁、并发、地道的Go代码。

When to Use

适用场景

  • Writing Go code
  • Concurrency patterns
  • Performance optimization
  • Interface design
  • Go module management
  • 编写Go代码
  • 并发模式实现
  • 性能优化
  • 接口设计
  • Go模块管理

Go Patterns

Go编程模式

Concurrency

并发编程

go
// Worker pool pattern
func workerPool(jobs <-chan Job, results chan<- Result, workers int) {
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for job := range jobs {
                results <- process(job)
            }
        }()
    }
    wg.Wait()
    close(results)
}

// Context for cancellation
func fetchWithTimeout(ctx context.Context, url string) ([]byte, error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}
go
// Worker pool pattern
func workerPool(jobs <-chan Job, results chan<- Result, workers int) {
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for job := range jobs {
                results <- process(job)
            }
        }()
    }
    wg.Wait()
    close(results)
}

// Context for cancellation
func fetchWithTimeout(ctx context.Context, url string) ([]byte, error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}

Error Handling

错误处理

go
// Custom errors with context
type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("%s: %s", e.Field, e.Message)
}

// Error wrapping
if err != nil {
    return fmt.Errorf("failed to process user %d: %w", userID, err)
}
go
// Custom errors with context
type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("%s: %s", e.Field, e.Message)
}

// Error wrapping
if err != nil {
    return fmt.Errorf("failed to process user %d: %w", userID, err)
}

Interfaces

接口设计

go
// Small, focused interfaces
type Reader interface {
    Read(p []byte) error
}

type Writer interface {
    Write(p []byte) error
}

// Composition
type ReadWriter interface {
    Reader
    Writer
}
go
// Small, focused interfaces
type Reader interface {
    Read(p []byte) error
}

type Writer interface {
    Write(p []byte) error
}

// Composition
type ReadWriter interface {
    Reader
    Writer
}

Project Structure

项目结构

project/
├── cmd/
│   └── app/
│       └── main.go
├── internal/
│   ├── handler/
│   └── service/
├── pkg/
│   └── utils/
├── go.mod
└── go.sum
project/
├── cmd/
│   └── app/
│       └── main.go
├── internal/
│   ├── handler/
│   └── service/
├── pkg/
│   └── utils/
├── go.mod
└── go.sum

Testing

测试

go
func TestProcess(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {"valid input", "hello", "HELLO", false},
        {"empty input", "", "", true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Process(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
            }
            if got != tt.want {
                t.Errorf("got %v, want %v", got, tt.want)
            }
        })
    }
}
go
func TestProcess(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {"valid input", "hello", "HELLO", false},
        {"empty input", "", "", true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Process(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
            }
            if got != tt.want {
                t.Errorf("got %v, want %v", got, tt.want)
            }
        })
    }
}

Best Practices

最佳实践

  • Prefer composition over inheritance
  • Keep interfaces small (1-3 methods)
  • Handle errors explicitly
  • Use context for cancellation
  • Avoid global state
  • 优先使用组合而非继承
  • 保持接口精简(1-3个方法)
  • 显式处理错误
  • 使用context进行取消操作
  • 避免全局状态

Examples

示例

Input: "Add concurrency to this" Action: Identify parallel work, add goroutines with proper sync, handle errors
Input: "Review this Go code" Action: Check error handling, interface design, concurrency safety
输入:"为这段代码添加并发功能" **操作:**识别可并行的任务,添加带同步机制的goroutines,处理错误
输入:"评审这段Go代码" **操作:**检查错误处理、接口设计、并发安全性