✨ Go Best Practices
Write idiomatic, maintainable, and efficient Go code.
Code Organization
- Keep packages small and focused
- Use meaningful package names
- Avoid circular dependencies
- Place main packages in cmd/ directory
- Keep internal packages in internal/
Error Handling
// Good if err != nil { return fmt.Errorf("failed to process: %w", err) } // Wrap errors with context err := doSomething() if err != nil { return fmt.Errorf("doSomething: %w", err) }
Interface Design
- Accept interfaces, return structs
- Keep interfaces small (1-3 methods)
- Define interfaces where they're used
- Use embedded interfaces for composition
Concurrency Guidelines
- Don't communicate by sharing memory; share memory by communicating
- Use channels for orchestration, mutexes for state
- Start goroutines in the function that creates them
- Always handle goroutine cleanup
Performance Tips
- Measure before optimizing (use benchmarks)
- Preallocate slices when size is known
- Use sync.Pool for frequently allocated objects
- Avoid unnecessary allocations in hot paths
- Profile your application regularly
Testing Best Practices
- Write table-driven tests
- Use subtests for better organization
- Keep tests close to the code
- Use testdata/ for test fixtures
- Mock external dependencies