Skills

Golang Patterns

构建健壮、高效且可维护 Go 应用程序的惯用法(Idiomatic Go)、最佳实践与规范。

Install

npx skills add xu-xiang/everything-claude-code-zh --skill golang-patterns -g -a claude-code -y
Category
Engineering
Updated
8mo ago
License
MIT
Context cost
Mediumabout 2,917 tokens
Runs scripts
No, instructions only

What it does

构建健壮、高效且可维护 Go 应用程序的惯用法(Idiomatic Go)、最佳实践与规范。

Go 开发模式(Go Development Patterns)

用于构建健壮、高效且可维护应用程序的惯用法与最佳实践。

何时启用

  • 编写新的 Go 代码时
  • 评审 Go 代码时
  • 重构现有 Go 代码时
  • 设计 Go 软件包(Package)/ 模块(Module)时

核心原则

1. 简单与清晰

Go 倾向于简单而非巧妙。代码应当直观且易读。

// Good: 清晰且直接
func GetUser(id string) (*User, error) {
    user, err := db.FindUser(id)
    if err != nil {
        return nil, fmt.Errorf("get user %s: %w", id, err)
    }
    return user, nil
}

// Bad: 过于巧妙
func GetUser(id string) (*User, error) {
    return func() (*User, error) {
        if u, e := db.FindUser(id); e == nil {
            return u, nil
        } else {
            return nil, e
        }
    }()
}

2. 让零值(Zero Value)变得有用

在设计类型时,应确保其零值无需显式初始化即可直接使用。

// Good: 零值很有用
type Counter struct {
    mu    sync.Mutex
    count int // 零值为 0,可直接使用
}

func (c *Counter) Inc() {
    c.mu.Lock()
    c.count++
    c.mu.Unlock()
}

// Good: bytes.Buffer 可以直接使用零值
var buf bytes.Buffer
buf.WriteString("hello")

// Bad: 需要初始化
type BadCounter struct {
    counts map[string]int // nil map 会引发 panic
}

3. 接受接口(Interface),返回结构体(Struct)

函数应当接收接口参数并返回具体类型。

// Good: 接收接口,返回具体类型
func ProcessData(r io.Reader) (*Result, error) {
    data, err := io.ReadAll(r)
    if err != nil {
        return nil, err
    }
    return &Result{Data: data}, nil
}

// Bad: 返回接口(无谓地隐藏了实现细节)
func ProcessData(r io.Reader) (io.Reader, error) {
    // ...
}

错误处理模式(Error Handling Patterns)

带有上下文的错误包装(Error Wrapping)

// Good: 使用上下文包装错误
func LoadConfig(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, fmt.Errorf("load config %s: %w", path, err)
    }

    var cfg Config
    if err := json.Unmarshal(data, &cfg); err != nil {
        return nil, fmt.Errorf("parse config %s: %w", path, err)
    }

    return &cfg, nil
}

自定义错误类型

// 定义领域特定错误
type ValidationError struct {
    Field   string
    Message string
}
Read the whole SKILL.md on GitHub

More in Engineering