| name | golang-expert |
| description | | Use when this capability is needed. |
Golang Expert
Expert guidance for writing clean, idiomatic, maintainable Go code.
Table of Contents
- Core Principles
- Quick Reference
- Detailed Guides
Core Principles
The Go Philosophy (KISS, DRY, YAGNI)
- Simplicity over cleverness - Readable beats clever
- Explicit over implicit - No magic, clear data flow
- Composition over inheritance - Small interfaces, embed structs
- Errors are values - Handle them, don't ignore them
KISS - Keep It Simple
type ProcessorFactory interface {
CreateProcessor(config Config) Processor
}
func Process(data []byte) (Result, error) {
}
DRY - Don't Repeat Yourself
func ParseUserDate(s string) time.Time { }
func ParseOrderDate(s string) time.Time { }
func ParseDate(s string) (time.Time, error) {
return time.Parse(time.RFC3339, s)
}
YAGNI - You Aren't Gonna Need It
Don't build for hypothetical future requirements. Only implement what's needed right now.
type DataProcessor interface {
Process(data []byte) ([]byte, error)
ProcessBatch(data [][]byte) ([][]byte, error)
ProcessAsync(data []byte, callback func([]byte, error))
ProcessWithOptions(data []byte, opts ProcessOptions) ([]byte, error)
}
type ProcessOptions struct {
Format string
Compression bool
Encryption bool
Retry int
Timeout time.Duration
Logger Logger
Metrics MetricsCollector
}
func Process(data []byte) ([]byte, error) {
}
YAGNI Anti-patterns to Avoid:
- Premature abstraction - Don't create interfaces until you have 2+ implementations
- Speculative generality - Don't add parameters "someone might need"
- Gold plating - Don't add features beyond requirements
- Framework thinking - You're building an app, not a framework
type UserRepository interface {
GetUser(id int) (*User, error)
}
type userRepositoryImpl struct { db *sql.DB }
type UserStore struct { db *sql.DB }
func (s *UserStore) GetUser(id int) (*User, error) { }
The Rule of Three: Don't abstract until you see the pattern three times.
Delete code freely. Unused code is a liability, not an asset. Version control remembers everything.
Functional Principles
- No global mutable state - Use dependency injection
- Immutability - Return new values, don't mutate inputs
- Pure functions - Same input = same output, no side effects
- Constants over variables - Use
const when possible
var logger *Logger
func SetLogger(l *Logger) { logger = l }
type Service struct {
logger Logger
}
func NewService(logger Logger) *Service {
return &Service{logger: logger}
}
Quick Reference
Interface Design
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
type ReadWriter interface {
Reader
Writer
}
func Process(r Reader) *Result { }
Error Handling
if err != nil {
return fmt.Errorf("process user %d: %w", id, err)
}
var ErrNotFound = errors.New("not found")
if errors.Is(err, ErrNotFound) { }
Table-Driven Tests
func TestParse(t *testing.T) {
tests := []struct {
name string
input string
want Result
wantErr bool
}{
{"valid input", "abc", Result{Value: "abc"}, false},
{"empty input", "", Result{}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Parse(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("Parse() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("Parse() = %v, want %v", got, tt.want)
}
})
}
}
Concurrency
func Process(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case result := <-work():
return handle(result)
}
}
g, ctx := errgroup.WithContext(ctx)
for _, item := range items {
item := item
g.Go(func() error { return process(ctx, item) })
}
return g.Wait()
Detailed Guides
Load these references as needed:
| Topic | File | When to Use |
|---|
| Functional Patterns | functional-patterns.md | DI, immutability, pure functions |
| KISS & DRY | kiss-dry.md | Simplification, code deduplication |
| Interface Design | interface-design.md | API design, interface segregation |
| Testing | testing.md | Tests, mocks, benchmarks |
| Error Handling | error-handling.md | Error patterns, wrapping, types |
| Concurrency | concurrency.md | Goroutines, channels, sync |
| Performance | performance.md | Profiling, optimization |
| Code Review | code-review-checklist.md | Review checklist |
Code Review Workflow
When reviewing Go code:
- Read code-review-checklist.md
- Check for KISS/DRY violations
- Verify error handling is complete
- Assess interface design
- Review test coverage and quality
- Flag concurrency issues
- Identify performance concerns
Refactoring Workflow
When refactoring:
- Ensure tests exist before changes
- Apply KISS - Remove unnecessary abstractions
- Apply DRY - Extract duplicated code
- Improve interfaces - Make them smaller
- Add DI - Remove global state
- Run tests after each change
Source: fjacquet/pdf2md — distributed by TomeVault.