AgentSkillsCN

go-patterns

Go语言的模式与惯用法——包结构、接口、错误处理、并发编程。适用于编写Go代码的场景。

SKILL.md
--- frontmatter
name: go-patterns
description: Go patterns and idioms - package structure, interfaces, error handling, concurrency. Use when writing Go code.

Go Patterns

File Structure

Order: packageimportconstvartype → functions/methods

Package Organization

text
project/
├── cmd/<name>/main.go    # Entry points
├── internal/<domain>/    # Private packages
│   ├── types.go          # Types, const, var, errors
│   ├── repository.go     # Interface + implementation
│   └── service.go        # Business logic
├── pkg/                  # Public packages
└── go.mod

Rules

  • No hardcoding - Use const, config, or inject
  • Interface at consumer - Define where used, not where implemented
  • Context first - Always first parameter, never store in struct
  • Errors wrapped - fmt.Errorf("context: %w", err)
  • Constructor pattern - func NewX(...) *X
  • Options pattern - func NewX(opts ...Option) *X for complex config
  • Table-driven tests - tests := []struct{ name, input, want }{...}

Concurrency

NeedPattern
Background workgo func() { ... }() with context
Multiple sourcesfor { select { case <-ctx.Done(): ... } }
Parallel ops with errorserrgroup.WithContext(ctx)
Shared statesync.Mutex
One-time initsync.Once
Wait for goroutinessync.WaitGroup
Streaming workchannels + worker pool
Fan-out/fan-inSee reference

See references/concurrency.go for Pool, FanOut, Merge, Semaphore.

References

Checklist

  • const/var at file top?
  • No hardcoded values?
  • Interface at consumer?
  • Context as first param?
  • Errors wrapped with context?
  • Table-driven tests?
  • Background work? → go func() with context
  • Multiple sources? → select { }
  • Parallel ops? → errgroup
  • Shared state? → sync.Mutex
  • One-time init? → sync.Once
  • Wait for goroutines? → sync.WaitGroup
  • Streaming work? → channels + worker pool