Go Idioms and Patterns
1. Core Philosophy
Go favors simplicity, explicitness, and readability. The language is intentionally small — resist the urge to import patterns from other languages. If it looks boring and obvious, it's probably idiomatic Go.
Scope: This file covers Go-specific coding idioms. For file layout, see references/project-structure.md. For detailed safety, SAST, and performance patterns, see references/go-patterns-and-anti-patterns.md. For logging library choice, see the logging-implementation skill. For quality commands, see the code-idioms-and-conventions rule.
Loading Guards: If the project has no go.mod, this skill does not apply.
2. When to Load References
| Situation |
Reference to Load |
| Starting a new project or setting up file layout |
references/project-structure.md |
Choosing packages, go.mod setup, or golangci-lint config |
references/recommended-dependencies.md |
| Writing code that handles I/O, concurrency, or user input |
references/go-patterns-and-anti-patterns.md |
3. Toolchain and Go Version
Default to the latest stable Go release. As of August 2026, Go 1.24 is the baseline with the Go module system.
Key version milestones:
- 1.24+ —
go tool for tool dependencies, swiss table map implementation
- 1.23+ —
range-over-func (iterator protocol), unique package
- 1.22+ —
range-over-integer, loop variable per-iteration scoping (eliminates loop variable capture bugs), enhanced ServeMux with method-based routing
- 1.21+ —
log/slog structured logging, maps and slices stdlib packages, sync.OnceFunc / sync.OnceValue / sync.OnceValues, min / max builtins, clear builtin
- 1.18+ — Generics, fuzz testing with
testing.F
Example go.mod configuration:
module github.com/user/project
go 1.24.0
toolchain go1.24.0
4. Error Handling
Always return errors — never panic in library or business code
panic is reserved for truly unrecoverable states (programmer errors, nil dereference)
- Use
recover only at top-level goroutine boundaries (middleware, server startup)
Wrap errors with context using %w
- Don't re-wrap at every level. Wrap once with meaningful context where it matters.
✅ Preserves the error chain for errors.Is / errors.As
return fmt.Errorf("creating task for user %s: %w", userID, err)
❌ Loses the error chain
return fmt.Errorf("creating task: %v", err)
Error string formatting
- Error strings should be lowercase and have no trailing punctuation.
- Go convention from Code Review Comments.
✅ Correct formatting
return fmt.Errorf("failed to open file %q: %w", path, err)
❌ Incorrect formatting
return fmt.Errorf("Failed to open file: %w.", err)
Use errors.Join for multi-error aggregation (Go 1.20+)
var errs []error
if err := doFirst(); err != nil {
errs = append(errs, err)
}
if err := doSecond(); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
Use sentinel errors for expected branch conditions
// Define in errors.go
var ErrNotFound = errors.New("not found")
var ErrUnauthorized = errors.New("unauthorized")
// Caller checks with errors.Is
if errors.Is(err, ErrNotFound) {
// handle
}
Use typed errors for rich domain errors
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message)
}
// Caller unwraps with errors.As
var ve *ValidationError
if errors.As(err, &ve) {
// access ve.Field, ve.Message
}
Handle errors at the right level
- Propagate upward until you have enough context to act on them; don't swallow or re-wrap the same error twice.
Use lazy evaluation for fallback values
- Prefer creating errors lazily only when a failure occurs to avoid unnecessary allocations.
5. Interfaces
Keep interfaces small — one or two methods is ideal
✅ Focused, composable
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
❌ Monolithic
type FileManager interface {
Read()
Write()
Delete()
List()
Stat()
}
"Accept interfaces, return structs"
- Function parameters: accept interfaces for flexibility and testability
- Return values: return concrete structs so callers can access all methods
Define interfaces where they are used, not where they are implemented
✅ Defined in the consumer package (task feature)
// task/storage.go
type Storage interface {
GetByID(ctx context.Context, id string) (*Task, error)
}
// postgres.go implements Storage — it does NOT define it
Implicit satisfaction is a feature — don't use embedding to "implement" interfaces
- Any type with the right method set satisfies an interface automatically
- No
implements keyword needed or wanted
any vs interface{}
- Always use
any (Go 1.18+ alias) instead of interface{}.
Interface compliance verification
- Use
var _ Interface = (*Struct)(nil) to guarantee a type implements an interface at compile time.
var _ Storage = (*PostgresStorage)(nil)
When NOT to use interfaces
- Premature abstraction violates YAGNI. Do not create an interface until you have 3+ implementations (or you need to mock it for testing in test-driven design).
Generic interfaces with type parameters (Go 1.18+)
type Repository[T any] interface {
FindByID(ctx context.Context, id string) (T, error)
}
6. Goroutines and Channels
For general concurrency principles (race conditions, deadlocks, message passing), see concurrency-and-threading-principles.md. This section covers Go-specific mechanics.
Always pass context.Context as the first parameter
✅ Pass context
func (s *Service) GetTask(ctx context.Context, id string) (*Task, error)
❌ No way to cancel or propagate deadlines
func (s *Service) GetTask(id string) (*Task, error)
Never start a goroutine without knowing how it will stop (Anti-pattern: Goroutine Leak)
- Every goroutine must have a definitive exit path (e.g., via
context.Context cancellation or channel close).
✅ Goroutine is bounded by context cancellation
go func() {
for {
select {
case <-ctx.Done():
return
case item := <-ch:
process(item)
}
}
}()
Goroutine lifecycle management with sync.WaitGroup
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(t Task) {
defer wg.Done()
process(t)
}(task)
}
wg.Wait()
Use errgroup for concurrent fan-out with error collection
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return fetchUsers(ctx) })
g.Go(func() error { return fetchOrders(ctx) })
if err := g.Wait(); err != nil { ... }
Prefer channels for ownership transfer; mutexes for shared state
- Channel: "I'm handing this data to you"
- Mutex: "We're both reading/writing this shared thing"
Close channels from the sender, never the receiver
context.AfterFunc (Go 1.21+)
- Trigger an action asynchronously when a context completes.
stop := context.AfterFunc(ctx, func() {
cleanupResources()
})
defer stop()
Channel direction restrictions in function signatures
- Narrow channel directions for compile-time safety.
func producer(ch chan<- int) {} // Send-only
func consumer(ch <-chan int) {} // Receive-only
sync.OnceFunc / sync.OnceValue (Go 1.21+)
- Use for lazy, thread-safe initialization.
var initDb = sync.OnceValue(func() *sql.DB {
// initialize DB
return db
})
select with default for non-blocking operations
select {
case ch <- data:
// Sent
default:
// Channel is full or unbuffered with no receiver, move on
}
context.WithoutCancel (Go 1.21+)
- Create a derived context that is not cancelled when the parent is. Use for background operations that must outlive the request (e.g., async audit logging, metrics flush).
// Request-scoped context cancelled when handler returns
bgCtx := context.WithoutCancel(ctx)
go func() {
// This work continues even after the parent request completes
auditLog(bgCtx, event)
}()
⚠️ Use sparingly — most work should respect parent cancellation. Reserve for fire-and-forget operations where partial completion is acceptable.
Structured concurrency with conc (when errgroup isn't enough)
errgroup covers fan-out with error collection. For additional needs — panic recovery within goroutines, bounded worker pools with panic safety — use github.com/sourcegraph/conc.
// conc.WaitGroup recovers panics and re-panics on Wait()
wg := conc.NewWaitGroup()
wg.Go(func() { process(item1) })
wg.Go(func() { process(item2) })
wg.Wait() // Re-panics if any goroutine panicked
- Prefer
errgroup for simple fan-out. Reach for conc when you need panic recovery or bounded concurrency with conc/pool.
7. Naming Conventions
Receiver names: short, consistent, and the first letter of the type
✅
func (s *Service) Create(...) {}
❌
func (svc *Service) Create(...) {} // too verbose
func (self *Service) Create(...) {} // not Go
Package names: short, lowercase, no underscores, no plurals
✅ package task
❌ package tasks (plural)
❌ package task_service (underscore)
Acronyms follow Go conventions (all caps or all lowercase)
✅ userID, HTTPClient
❌ userId, HttpClient
Unexported identifiers omit the type name — if it's private, keep it terse
Don't stutter — task.Task is fine; task.TaskService is not
Error string formatting
- Error strings should not be capitalized or end with punctuation.
Getter naming
- No
Get prefix in Go. Use user.Name() not user.GetName().
Test naming
- Use the
TestFunctionName_Scenario_Expected pattern.
func TestCalculateDiscount_NegativeInput_ReturnsError(t *testing.T) { ... }
Constructor naming
- Use
New prefix (NewService, NewClient).
Interface naming
- Use the
-er suffix for single-method interfaces (Reader, Writer, Stringer).
8. Idiomatic Patterns
Range-over-func iterators (Go 1.23+)
// Definition
func Count(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := 0; i < n; i++ {
if !yield(i) {
return
}
}
}
}
// Usage
for i := range Count(5) {
fmt.Println(i)
}
Nil slice vs empty slice semantics
var s []int (nil slice) marshals to null in JSON.
s := []int{} or make([]int, 0) (empty slice) marshals to [] in JSON.
Type assertions with comma-ok pattern
if str, ok := val.(string); ok {
fmt.Println(str)
}
Type switches for polymorphic dispatch
switch v := val.(type) {
case string:
fmt.Println("String:", v)
case int:
fmt.Println("Int:", v)
default:
fmt.Println("Unknown type")
}
strings.Builder for string concatenation
- Avoid
+ inside loops. Use strings.Builder.
var b strings.Builder
b.WriteString("hello")
b.WriteString("world")
return b.String()
slices and maps stdlib packages (Go 1.21+)
- Use the built-in generic functions for sorting, reversing, filtering, and checking elements.
slices.Sort(mySlice)
if slices.Contains(mySlice, target) { ... }
Variadic append
- Use
append(s1, s2...) instead of loops.
Pre-allocation
- Use
make([]T, 0, n) when the size is known to avoid reallocation overhead.
sync.Pool for hot-path allocations
- Use only for POINTER values to reduce GC pressure.
time.NewTicker vs time.Tick
time.Tick leaks the underlying ticker. Always prefer time.NewTicker which can be stopped via ticker.Stop().
Struct embedding for composition (not inheritance)
- Use struct embedding to reuse fields and methods where it forms an "is-a" relationship, not for general code reuse.
Early returns / guard clauses
if err != nil {
return err
}
// Continue happy path
Keep function complexity low
- Keep cyclomatic complexity under 10 (matching Rust/TS guidelines).
Functional options for optional configuration
type Option func(*Service)
func WithTimeout(d time.Duration) Option {
return func(s *Service) { s.timeout = d }
}
func NewService(store Storage, opts ...Option) *Service {
s := &Service{store: store, timeout: 30 * time.Second}
for _, o := range opts { o(s) }
return s
}
defer for cleanup — always use error-checked closures
Every deferred cleanup call that returns an error MUST check and log the error.
Never use bare defer X.Close() — the discarded error hides resource leak failures.
❌ NEVER: Error silently discarded
defer rows.Close()
✅ ALWAYS: Error-checked closure with structured logging
rows, err := db.QueryContext(ctx, query)
if err != nil { return fmt.Errorf("querying tasks: %w", err) }
defer func() {
if err := rows.Close(); err != nil {
slog.Warn("failed to close rows", "error", err, "operation", "ListTasks")
}
}()
Transaction rollback:
❌ NEVER
defer tx.Rollback()
✅ ALWAYS: Guard against sql.ErrTxDone (already committed)
defer func() {
if err := tx.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) {
slog.Error("failed to rollback transaction", "error", err, "operation", "CreateOrder")
}
}()
HTTP response body:
❌ NEVER
defer resp.Body.Close()
✅ ALWAYS: Drain then close (prevents connection reuse issues)
defer func() {
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
slog.Warn("failed to drain response body", "error", err)
}
if err := resp.Body.Close(); err != nil {
slog.Warn("failed to close response body", "error", err)
}
}()
Avoid init() functions
- They run implicitly and make testing harder; prefer explicit initialization in
main or constructors.
Use named return values only for documentation or defer-based cleanup
- Never rely on naked returns in non-trivial functions.
unique.Handle for string interning (Go 1.23+)
- Deduplicate frequently repeated values (user IDs, status strings) to reduce memory.
import "unique"
h := unique.Make("active")
// h.Value() returns "active"
// Two handles with the same underlying value compare as equal
h1 := unique.Make("active")
fmt.Println(h == h1) // true — same canonical representation
- Use when you have many copies of the same string in memory (e.g., status enums parsed from JSON). Don't use for unique values — the interning overhead is wasted.
9. Testing
Test file naming and pyramid proportions are defined in testing-strategy.md. This section covers Go-specific tooling only.
Table-driven tests are the default pattern
func TestCalculateDiscount(t *testing.T) {
tests := []struct {
name string
input float64
expected float64
wantErr bool
}{
{"zero items", 0, 0, false},
{"negative input", -1, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := calculateDiscount(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.expected, got)
})
}
}
Use testify for assertions
require for fatal assertions, assert for non-fatal.
Run with the race detector in CI
Use httptest.NewRecorder() for HTTP handler tests
Test behaviour, not implementation
- Assert on outputs and side effects, not internal field values.
Test helpers with t.Helper() and testing.TB interface
func createTestUser(t testing.TB) *User {
t.Helper() // Corrects line numbers in failure output
// ...
}
t.Cleanup() for resource teardown
- Automatically cleans up resources without needing defers across multiple helper functions.
func setupDB(t *testing.T) *sql.DB {
db := connect()
t.Cleanup(func() { db.Close() })
return db
}
Fuzz testing with testing.F (Go 1.18+)
func FuzzParse(f *testing.F) {
f.Add("valid_input")
f.Fuzz(func(t *testing.T, input string) {
Parse(input) // ensure it never panics
})
}
Benchmark patterns with testing.B
func BenchmarkProcess(b *testing.B) {
b.ReportAllocs() // ALWAYS report allocations
b.ResetTimer() // Ignore setup time
for i := 0; i < b.N; i++ {
Process()
}
}
Golden file testing
- For large, complex outputs (like JSON or HTML), use golden files and compare against them.
Test coverage non-negotiable policy
- Every new exported function/method MUST have tests.
- Every branch MUST be exercised.
Coverage commands
- Run
go test -cover ./... and go test -coverprofile=coverage.out ./....
Test Double Selection Table
| Approach |
When to Use |
| Hand-written fake (implement interface) |
Simple interface, few methods, need stateful behavior |
gomock/mockgen |
Complex interface, need to verify call counts, argument matching |
testify/mock |
Complex interface, prefer fluent assertion API |
| Table-driven tests |
Same logic, multiple input/output pairs |
go-cmp |
Deep equality comparison with custom options |
Prefer hand-written fakes for core domain traits.
10. Formatting and Static Analysis
All of the following must pass with zero warnings/errors before any commit. See code-idioms-and-conventions.md for the full checklist.
Feedback Loop — Development Workflow:
| Phase |
Command |
Purpose |
| TDD / rapid iteration |
go vet ./... |
Type-checks and correctness — fastest loop |
| Pre-commit |
golangci-lint run |
Aggregated linting — must pass zero warnings |
| Pre-commit |
gofumpt -l -w . |
Formatting — non-negotiable |
| Pre-commit |
go test -race ./... |
Unit tests with race detector |
| Coverage verification |
go test -coverprofile=c.out ./... |
Verify before merging |
| Security audit |
govulncheck ./... |
CVE scanning |
Lint suppression policy — NEVER suppress these:
| Lint |
What It Signals |
What To Do Instead |
errcheck |
Unchecked error returns |
Handle the error — use error-checked closure in defer |
govet shadow |
Variable shadowing |
Rename the inner variable |
staticcheck SA* |
Correctness issues |
Fix the underlying bug |
gosec G* (security) |
Security vulnerability |
Fix the vulnerability |
cyclop / gocognit |
Function too complex |
Decompose into smaller functions |
Acceptable suppressions (with mandatory // nolint: comment + rationale):
| Lint |
When Acceptable |
gosec G104 (unhandled error) |
In test code only, with // nolint:gosec // test-only |
revive exported |
When the exported symbol is intentionally part of API design |
Rule of thumb: If you're about to write //nolint:, stop and ask if you're suppressing a real design problem.
//nolint:errcheck is NEVER acceptable. If a function returns an error, handle it — even in defer. Use an error-checked closure. This is the #1 source of audit findings.
Logging: Never use fmt.Println or log.Printf in production service code — these produce unstructured output. Use log/slog (stdlib, Go 1.21+) or the project's chosen adapter. See @.agents/skills/logging-implementation/SKILL.md for the required library and patterns.
11. Documentation
Godoc conventions
- Package-level doc comment should exist for all exported packages.
- All exported symbols (functions, structs, interfaces, vars, consts) MUST have a documentation comment starting with the name of the symbol.
Example functions
- Use
func ExampleFunction() with // Output: comments at the end of the function body for runnable examples in Godoc.
func ExampleHello() {
fmt.Println("Hello")
// Output: Hello
}
Package doc
- For complex packages, place package documentation in a dedicated
doc.go file.
Document the WHY, not the WHAT
- The code shows what is happening. Comments explain why it is done this way (design rationale, edge cases, workarounds).
12. Dependency Management
Minimize dependency count
- Go stdlib is highly comprehensive. Rely on it heavily before bringing in external packages.
Commit go.sum always
- Both
go.mod and go.sum belong in version control to guarantee reproducible builds.
go mod tidy before commits
- Always run this to prune unused dependencies and resolve checksums.
govulncheck in CI
- Continuously scan for vulnerabilities in your module dependency tree.
Module proxy and checksum database
- Use
GOPROXY and the checksum database. For private modules, configure GOPRIVATE or GONOSUMCHECK.
Prefer stdlib over third-party
- When feature parity exists (e.g.,
log/slog vs zap), use the stdlib.
13. Configuration and Environment
Never scatter os.Getenv() calls throughout codebase
- It makes dependencies opaque and testing difficult.
Centralized config struct parsed at startup
- Parse all configurations into a central
Config struct once, then inject it (or its subsets) where needed.
Fail fast
- Fail at boot for missing required configuration, not later at the first time of use.
Example with struct tags and validation
type Config struct {
Port int `env:"PORT" envDefault:"8080"`
Database string `env:"DATABASE_URL" envRequired:"true"`
}
func LoadConfig() (*Config, error) {
// load and validate
}
14. Safety, Security, and Performance
- Key safety rules (non-negotiable):
- Never ignore errors.
- Always close resources safely in a
defer.
- Validate all user input at the system boundary.
- For a full catalog: Point to
references/go-patterns-and-anti-patterns.md.
- For Go-specific profiling: Point to the
perf-optimization skill.
15. Related Principles
- Code Idioms and Conventions @code-idioms-and-conventions.md
- Project Structure — Go Backend @references/project-structure.md
- Security Principles @security-principles.md
- Architectural Patterns — Testability-First Design @architectural-pattern.md
- Testing Strategy @testing-strategy.md
- Error Handling Principles @error-handling-principles.md
- Concurrency and Threading Principles @concurrency-and-threading-principles.md
- Logging and Observability Mandate @logging-and-observability-mandate.md
- Logging and Observability Principles @.agents/skills/logging-implementation/SKILL.md
- Dependency Management Principles @dependency-management-principles.md
1---2name: go-idioms-23description: Go stdlib, error wrapping, interfaces, goroutines, table-driven tests, gofumpt.4---56## Go Idioms and Patterns78### 1. Core Philosophy910Go favors simplicity, explicitness, and readability. The language is intentionally small — resist the urge to import patterns from other languages. If it looks boring and obvious, it's probably idiomatic Go.1112> **Scope:** This file covers Go-specific *coding idioms*. For file layout, see `references/project-structure.md`. For detailed safety, SAST, and performance patterns, see `references/go-patterns-and-anti-patterns.md`. For logging library choice, see the `logging-implementation` skill. For quality commands, see the `code-idioms-and-conventions` rule.1314**Loading Guards:** If the project has no `go.mod`, this skill does not apply.1516---1718### 2. When to Load References1920| Situation | Reference to Load |21|---|---|22| Starting a new project or setting up file layout | `references/project-structure.md` |23| Choosing packages, `go.mod` setup, or `golangci-lint` config | `references/recommended-dependencies.md` |24| Writing code that handles I/O, concurrency, or user input | `references/go-patterns-and-anti-patterns.md` |2526---2728### 3. Toolchain and Go Version2930Default to the latest stable Go release. As of August 2026, **Go 1.24** is the baseline with the Go module system.3132Key version milestones:33- **1.24+** — `go tool` for tool dependencies, swiss table map implementation34- **1.23+** — `range`-over-func (iterator protocol), `unique` package35- **1.22+** — `range`-over-integer, loop variable per-iteration scoping (eliminates loop variable capture bugs), enhanced `ServeMux` with method-based routing36- **1.21+** — `log/slog` structured logging, `maps` and `slices` stdlib packages, `sync.OnceFunc` / `sync.OnceValue` / `sync.OnceValues`, `min` / `max` builtins, `clear` builtin37- **1.18+** — Generics, fuzz testing with `testing.F`3839**Example `go.mod` configuration:**40```go41module github.com/user/project4243go 1.24.04445toolchain go1.24.046```4748---4950### 4. Error Handling51521. **Always return errors — never panic in library or business code**53 - `panic` is reserved for truly unrecoverable states (programmer errors, nil dereference)54 - Use `recover` only at top-level goroutine boundaries (middleware, server startup)55562. **Wrap errors with context using `%w`**57 - Don't re-wrap at every level. Wrap once with meaningful context where it matters.58 59 ✅ Preserves the error chain for errors.Is / errors.As60 ```go61 return fmt.Errorf("creating task for user %s: %w", userID, err)62 ```6364 ❌ Loses the error chain65 ```go66 return fmt.Errorf("creating task: %v", err)67 ```68693. **Error string formatting**70 - Error strings should be lowercase and have no trailing punctuation.71 - Go convention from Code Review Comments.7273 ✅ Correct formatting74 ```go75 return fmt.Errorf("failed to open file %q: %w", path, err)76 ```7778 ❌ Incorrect formatting79 ```go80 return fmt.Errorf("Failed to open file: %w.", err)81 ```82834. **Use `errors.Join` for multi-error aggregation (Go 1.20+)**84 ```go85 var errs []error86 if err := doFirst(); err != nil {87 errs = append(errs, err)88 }89 if err := doSecond(); err != nil {90 errs = append(errs, err)91 }92 return errors.Join(errs...)93 ```94955. **Use sentinel errors for expected branch conditions**96 ```go97 // Define in errors.go98 var ErrNotFound = errors.New("not found")99 var ErrUnauthorized = errors.New("unauthorized")100101 // Caller checks with errors.Is102 if errors.Is(err, ErrNotFound) {103 // handle104 }105 ```1061076. **Use typed errors for rich domain errors**108 ```go109 type ValidationError struct {110 Field string111 Message string112 }113 func (e *ValidationError) Error() string {114 return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message)115 }116117 // Caller unwraps with errors.As118 var ve *ValidationError119 if errors.As(err, &ve) {120 // access ve.Field, ve.Message121 }122 ```1231247. **Handle errors at the right level** 125 - Propagate upward until you have enough context to act on them; don't swallow or re-wrap the same error twice.1261278. **Use lazy evaluation for fallback values**128 - Prefer creating errors lazily only when a failure occurs to avoid unnecessary allocations.129130---131132### 5. Interfaces1331341. **Keep interfaces small — one or two methods is ideal**135136 ✅ Focused, composable137 ```go138 type Reader interface { Read(p []byte) (n int, err error) }139 type Writer interface { Write(p []byte) (n int, err error) }140 ```141142 ❌ Monolithic143 ```go144 type FileManager interface {145 Read()146 Write()147 Delete()148 List()149 Stat()150 }151 ```1521532. **"Accept interfaces, return structs"**154 - Function parameters: accept interfaces for flexibility and testability155 - Return values: return concrete structs so callers can access all methods1561573. **Define interfaces where they are *used*, not where they are *implemented***158159 ✅ Defined in the consumer package (task feature)160 ```go161 // task/storage.go162 type Storage interface {163 GetByID(ctx context.Context, id string) (*Task, error)164 }165166 // postgres.go implements Storage — it does NOT define it167 ```1681694. **Implicit satisfaction is a feature — don't use embedding to "implement" interfaces**170 - Any type with the right method set satisfies an interface automatically171 - No `implements` keyword needed or wanted1721735. **`any` vs `interface{}`**174 - Always use `any` (Go 1.18+ alias) instead of `interface{}`.1751766. **Interface compliance verification**177 - Use `var _ Interface = (*Struct)(nil)` to guarantee a type implements an interface at compile time.178 ```go179 var _ Storage = (*PostgresStorage)(nil)180 ```1811827. **When NOT to use interfaces**183 - Premature abstraction violates YAGNI. Do not create an interface until you have 3+ implementations (or you need to mock it for testing in test-driven design).1841858. **Generic interfaces with type parameters (Go 1.18+)**186 ```go187 type Repository[T any] interface {188 FindByID(ctx context.Context, id string) (T, error)189 }190 ```191192---193194### 6. Goroutines and Channels195196> For general concurrency principles (race conditions, deadlocks, message passing), see `concurrency-and-threading-principles.md`. This section covers Go-specific mechanics.1971981. **Always pass `context.Context` as the first parameter**199200 ✅ Pass context201 ```go202 func (s *Service) GetTask(ctx context.Context, id string) (*Task, error)203 ```204205 ❌ No way to cancel or propagate deadlines206 ```go207 func (s *Service) GetTask(id string) (*Task, error)208 ```2092102. **Never start a goroutine without knowing how it will stop (Anti-pattern: Goroutine Leak)**211 - Every goroutine must have a definitive exit path (e.g., via `context.Context` cancellation or channel close).212213 ✅ Goroutine is bounded by context cancellation214 ```go215 go func() {216 for {217 select {218 case <-ctx.Done():219 return220 case item := <-ch:221 process(item)222 }223 }224 }()225 ```2262273. **Goroutine lifecycle management with `sync.WaitGroup`**228 ```go229 var wg sync.WaitGroup230 for _, task := range tasks {231 wg.Add(1)232 go func(t Task) {233 defer wg.Done()234 process(t)235 }(task)236 }237 wg.Wait()238 ```2392404. **Use `errgroup` for concurrent fan-out with error collection**241 ```go242 g, ctx := errgroup.WithContext(ctx)243 g.Go(func() error { return fetchUsers(ctx) })244 g.Go(func() error { return fetchOrders(ctx) })245 if err := g.Wait(); err != nil { ... }246 ```2472485. **Prefer channels for ownership transfer; mutexes for shared state**249 - Channel: "I'm handing this data to you"250 - Mutex: "We're both reading/writing this shared thing"2512526. **Close channels from the sender, never the receiver**2532547. **`context.AfterFunc` (Go 1.21+)**255 - Trigger an action asynchronously when a context completes.256 ```go257 stop := context.AfterFunc(ctx, func() {258 cleanupResources()259 })260 defer stop()261 ```2622638. **Channel direction restrictions in function signatures**264 - Narrow channel directions for compile-time safety.265 ```go266 func producer(ch chan<- int) {} // Send-only267 func consumer(ch <-chan int) {} // Receive-only268 ```2692709. **`sync.OnceFunc` / `sync.OnceValue` (Go 1.21+)**271 - Use for lazy, thread-safe initialization.272 ```go273 var initDb = sync.OnceValue(func() *sql.DB {274 // initialize DB275 return db276 })277 ```27827910. **`select` with `default` for non-blocking operations**280 ```go281 select {282 case ch <- data:283 // Sent284 default:285 // Channel is full or unbuffered with no receiver, move on286 }287 ```28828911. **`context.WithoutCancel` (Go 1.21+)**290 - Create a derived context that is not cancelled when the parent is. Use for background operations that must outlive the request (e.g., async audit logging, metrics flush).291 ```go292 // Request-scoped context cancelled when handler returns293 bgCtx := context.WithoutCancel(ctx)294 go func() {295 // This work continues even after the parent request completes296 auditLog(bgCtx, event)297 }()298 ```299 ⚠️ Use sparingly — most work should respect parent cancellation. Reserve for fire-and-forget operations where partial completion is acceptable.30030112. **Structured concurrency with `conc` (when `errgroup` isn't enough)**302 - `errgroup` covers fan-out with error collection. For additional needs — panic recovery within goroutines, bounded worker pools with panic safety — use `github.com/sourcegraph/conc`.303 ```go304 // conc.WaitGroup recovers panics and re-panics on Wait()305 wg := conc.NewWaitGroup()306 wg.Go(func() { process(item1) })307 wg.Go(func() { process(item2) })308 wg.Wait() // Re-panics if any goroutine panicked309 ```310 - Prefer `errgroup` for simple fan-out. Reach for `conc` when you need panic recovery or bounded concurrency with `conc/pool`.311312---313314### 7. Naming Conventions3153161. **Receiver names: short, consistent, and the first letter of the type**317 ✅318 ```go319 func (s *Service) Create(...) {}320 ```321 ❌322 ```go323 func (svc *Service) Create(...) {} // too verbose324 func (self *Service) Create(...) {} // not Go325 ```3263272. **Package names: short, lowercase, no underscores, no plurals**328 ✅ `package task`329 ❌ `package tasks` (plural)330 ❌ `package task_service` (underscore)3313323. **Acronyms follow Go conventions (all caps or all lowercase)**333 ✅ `userID`, `HTTPClient`334 ❌ `userId`, `HttpClient`3353364. **Unexported identifiers omit the type name** — if it's private, keep it terse3373385. **Don't stutter** — `task.Task` is fine; `task.TaskService` is not3393406. **Error string formatting**341 - Error strings should not be capitalized or end with punctuation.3423437. **Getter naming**344 - No `Get` prefix in Go. Use `user.Name()` not `user.GetName()`.3453468. **Test naming**347 - Use the `TestFunctionName_Scenario_Expected` pattern.348 ```go349 func TestCalculateDiscount_NegativeInput_ReturnsError(t *testing.T) { ... }350 ```3513529. **Constructor naming**353 - Use `New` prefix (`NewService`, `NewClient`).35435510. **Interface naming**356 - Use the `-er` suffix for single-method interfaces (`Reader`, `Writer`, `Stringer`).357358---359360### 8. Idiomatic Patterns3613621. **Range-over-func iterators (Go 1.23+)**363 ```go364 // Definition365 func Count(n int) iter.Seq[int] {366 return func(yield func(int) bool) {367 for i := 0; i < n; i++ {368 if !yield(i) {369 return370 }371 }372 }373 }374375 // Usage376 for i := range Count(5) {377 fmt.Println(i)378 }379 ```3803812. **Nil slice vs empty slice semantics**382 - `var s []int` (nil slice) marshals to `null` in JSON.383 - `s := []int{}` or `make([]int, 0)` (empty slice) marshals to `[]` in JSON.3843853. **Type assertions with comma-ok pattern**386 ```go387 if str, ok := val.(string); ok {388 fmt.Println(str)389 }390 ```3913924. **Type switches for polymorphic dispatch**393 ```go394 switch v := val.(type) {395 case string:396 fmt.Println("String:", v)397 case int:398 fmt.Println("Int:", v)399 default:400 fmt.Println("Unknown type")401 }402 ```4034045. **`strings.Builder` for string concatenation**405 - Avoid `+` inside loops. Use `strings.Builder`.406 ```go407 var b strings.Builder408 b.WriteString("hello")409 b.WriteString("world")410 return b.String()411 ```4124136. **`slices` and `maps` stdlib packages (Go 1.21+)**414 - Use the built-in generic functions for sorting, reversing, filtering, and checking elements.415 ```go416 slices.Sort(mySlice)417 if slices.Contains(mySlice, target) { ... }418 ```4194207. **Variadic append**421 - Use `append(s1, s2...)` instead of loops.4224238. **Pre-allocation**424 - Use `make([]T, 0, n)` when the size is known to avoid reallocation overhead.4254269. **`sync.Pool` for hot-path allocations**427 - Use only for POINTER values to reduce GC pressure.42842910. **`time.NewTicker` vs `time.Tick`**430 - `time.Tick` leaks the underlying ticker. Always prefer `time.NewTicker` which can be stopped via `ticker.Stop()`.43143211. **Struct embedding for composition (not inheritance)**433 - Use struct embedding to reuse fields and methods where it forms an "is-a" relationship, not for general code reuse.43443512. **Early returns / guard clauses**436 - Reduce nesting.437 ```go438 if err != nil {439 return err440 }441 // Continue happy path442 ```44344413. **Keep function complexity low**445 - Keep cyclomatic complexity under 10 (matching Rust/TS guidelines).44644714. **Functional options for optional configuration**448 ```go449 type Option func(*Service)450451 func WithTimeout(d time.Duration) Option {452 return func(s *Service) { s.timeout = d }453 }454455 func NewService(store Storage, opts ...Option) *Service {456 s := &Service{store: store, timeout: 30 * time.Second}457 for _, o := range opts { o(s) }458 return s459 }460 ```46146215. **`defer` for cleanup — always use error-checked closures**463464 Every deferred cleanup call that returns an error MUST check and log the error.465 Never use bare `defer X.Close()` — the discarded error hides resource leak failures.466467 ❌ NEVER: Error silently discarded468 ```go469 defer rows.Close()470 ```471472 ✅ ALWAYS: Error-checked closure with structured logging473 ```go474 rows, err := db.QueryContext(ctx, query)475 if err != nil { return fmt.Errorf("querying tasks: %w", err) }476 defer func() {477 if err := rows.Close(); err != nil {478 slog.Warn("failed to close rows", "error", err, "operation", "ListTasks")479 }480 }()481 ```482483 **Transaction rollback:**484 ❌ NEVER485 ```go486 defer tx.Rollback()487 ```488489 ✅ ALWAYS: Guard against sql.ErrTxDone (already committed)490 ```go491 defer func() {492 if err := tx.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) {493 slog.Error("failed to rollback transaction", "error", err, "operation", "CreateOrder")494 }495 }()496 ```497498 **HTTP response body:**499 ❌ NEVER500 ```go501 defer resp.Body.Close()502 ```503504 ✅ ALWAYS: Drain then close (prevents connection reuse issues)505 ```go506 defer func() {507 if _, err := io.Copy(io.Discard, resp.Body); err != nil {508 slog.Warn("failed to drain response body", "error", err)509 }510 if err := resp.Body.Close(); err != nil {511 slog.Warn("failed to close response body", "error", err)512 }513 }()514 ```51551616. **Avoid `init()` functions** 517 - They run implicitly and make testing harder; prefer explicit initialization in `main` or constructors.51851917. **Use named return values only for documentation or `defer`-based cleanup** 520 - Never rely on naked returns in non-trivial functions.52152218. **`unique.Handle` for string interning (Go 1.23+)**523 - Deduplicate frequently repeated values (user IDs, status strings) to reduce memory.524 ```go525 import "unique"526527 h := unique.Make("active")528 // h.Value() returns "active"529 // Two handles with the same underlying value compare as equal530 h1 := unique.Make("active")531 fmt.Println(h == h1) // true — same canonical representation532 ```533 - Use when you have many copies of the same string in memory (e.g., status enums parsed from JSON). Don't use for unique values — the interning overhead is wasted.534535---536537### 9. Testing538539> Test file naming and pyramid proportions are defined in `testing-strategy.md`. This section covers Go-specific tooling only.5405411. **Table-driven tests are the default pattern**542 ```go543 func TestCalculateDiscount(t *testing.T) {544 tests := []struct {545 name string546 input float64547 expected float64548 wantErr bool549 }{550 {"zero items", 0, 0, false},551 {"negative input", -1, 0, true},552 }553 for _, tt := range tests {554 t.Run(tt.name, func(t *testing.T) {555 got, err := calculateDiscount(tt.input)556 if tt.wantErr {557 require.Error(t, err)558 return559 }560 require.NoError(t, err)561 assert.Equal(t, tt.expected, got)562 })563 }564 }565 ```5665672. **Use `testify` for assertions** 568 - `require` for fatal assertions, `assert` for non-fatal.5695703. **Run with the race detector in CI** 571 - `go test -race ./...`5725734. **Use `httptest.NewRecorder()` for HTTP handler tests** 574 - No live server needed.5755765. **Test behaviour, not implementation** 577 - Assert on outputs and side effects, not internal field values.5785796. **Test helpers with `t.Helper()` and `testing.TB` interface**580 ```go581 func createTestUser(t testing.TB) *User {582 t.Helper() // Corrects line numbers in failure output583 // ...584 }585 ```5865877. **`t.Cleanup()` for resource teardown**588 - Automatically cleans up resources without needing defers across multiple helper functions.589 ```go590 func setupDB(t *testing.T) *sql.DB {591 db := connect()592 t.Cleanup(func() { db.Close() })593 return db594 }595 ```5965978. **Fuzz testing with `testing.F` (Go 1.18+)**598 ```go599 func FuzzParse(f *testing.F) {600 f.Add("valid_input")601 f.Fuzz(func(t *testing.T, input string) {602 Parse(input) // ensure it never panics603 })604 }605 ```6066079. **Benchmark patterns with `testing.B`**608 ```go609 func BenchmarkProcess(b *testing.B) {610 b.ReportAllocs() // ALWAYS report allocations611 b.ResetTimer() // Ignore setup time612 for i := 0; i < b.N; i++ {613 Process()614 }615 }616 ```61761810. **Golden file testing**619 - For large, complex outputs (like JSON or HTML), use golden files and compare against them.62062111. **Test coverage non-negotiable policy**622 - Every new exported function/method MUST have tests.623 - Every branch MUST be exercised.62462512. **Coverage commands**626 - Run `go test -cover ./...` and `go test -coverprofile=coverage.out ./...`.62762813. **Test Double Selection Table**629630| Approach | When to Use |631|---|---|632| Hand-written fake (implement interface) | Simple interface, few methods, need stateful behavior |633| `gomock`/`mockgen` | Complex interface, need to verify call counts, argument matching |634| `testify/mock` | Complex interface, prefer fluent assertion API |635| Table-driven tests | Same logic, multiple input/output pairs |636| `go-cmp` | Deep equality comparison with custom options |637638Prefer hand-written fakes for core domain traits.639640---641642### 10. Formatting and Static Analysis643644All of the following **must pass with zero warnings/errors** before any commit. See `code-idioms-and-conventions.md` for the full checklist.645646**Feedback Loop — Development Workflow:**647648| Phase | Command | Purpose |649|---|---|---|650| TDD / rapid iteration | `go vet ./...` | Type-checks and correctness — fastest loop |651| Pre-commit | `golangci-lint run` | Aggregated linting — must pass zero warnings |652| Pre-commit | `gofumpt -l -w .` | Formatting — non-negotiable |653| Pre-commit | `go test -race ./...` | Unit tests with race detector |654| Coverage verification | `go test -coverprofile=c.out ./...` | Verify before merging |655| Security audit | `govulncheck ./...` | CVE scanning |656657**Lint suppression policy — NEVER suppress these:**658659| Lint | What It Signals | What To Do Instead |660|---|---|---|661| `errcheck` | Unchecked error returns | Handle the error — use error-checked closure in defer |662| `govet` shadow | Variable shadowing | Rename the inner variable |663| `staticcheck` SA* | Correctness issues | Fix the underlying bug |664| `gosec` G* (security) | Security vulnerability | Fix the vulnerability |665| `cyclop` / `gocognit` | Function too complex | Decompose into smaller functions |666667**Acceptable suppressions (with mandatory `// nolint:` comment + rationale):**668669| Lint | When Acceptable |670|---|---|671| `gosec G104` (unhandled error) | In test code only, with `// nolint:gosec // test-only` |672| `revive exported` | When the exported symbol is intentionally part of API design |673674**Rule of thumb:** If you're about to write `//nolint:`, stop and ask if you're suppressing a real design problem.675676**`//nolint:errcheck` is NEVER acceptable.** If a function returns an error, handle it — even in `defer`. Use an error-checked closure. This is the #1 source of audit findings.677678> **Logging:** Never use `fmt.Println` or `log.Printf` in production service code — these produce unstructured output. Use `log/slog` (stdlib, Go 1.21+) or the project's chosen adapter. See `@.agents/skills/logging-implementation/SKILL.md` for the required library and patterns.679680---681682### 11. Documentation6836841. **Godoc conventions**685 - Package-level doc comment should exist for all exported packages.686 - All exported symbols (functions, structs, interfaces, vars, consts) MUST have a documentation comment starting with the name of the symbol.6876882. **Example functions**689 - Use `func ExampleFunction()` with `// Output:` comments at the end of the function body for runnable examples in Godoc.690 ```go691 func ExampleHello() {692 fmt.Println("Hello")693 // Output: Hello694 }695 ```6966973. **Package doc**698 - For complex packages, place package documentation in a dedicated `doc.go` file.6997004. **Document the WHY, not the WHAT**701 - The code shows *what* is happening. Comments explain *why* it is done this way (design rationale, edge cases, workarounds).702703---704705### 12. Dependency Management7067071. **Minimize dependency count**708 - Go stdlib is highly comprehensive. Rely on it heavily before bringing in external packages.7097102. **Commit `go.sum` always**711 - Both `go.mod` and `go.sum` belong in version control to guarantee reproducible builds.7127133. **`go mod tidy` before commits**714 - Always run this to prune unused dependencies and resolve checksums.7157164. **`govulncheck` in CI**717 - Continuously scan for vulnerabilities in your module dependency tree.7187195. **Module proxy and checksum database**720 - Use `GOPROXY` and the checksum database. For private modules, configure `GOPRIVATE` or `GONOSUMCHECK`.7217226. **Prefer stdlib over third-party**723 - When feature parity exists (e.g., `log/slog` vs `zap`), use the stdlib.724725---726727### 13. Configuration and Environment7287291. **Never scatter `os.Getenv()` calls throughout codebase**730 - It makes dependencies opaque and testing difficult.7317322. **Centralized config struct parsed at startup**733 - Parse all configurations into a central `Config` struct once, then inject it (or its subsets) where needed.7347353. **Fail fast**736 - Fail at boot for missing required configuration, not later at the first time of use.7377384. **Example with struct tags and validation**739 ```go740 type Config struct {741 Port int `env:"PORT" envDefault:"8080"`742 Database string `env:"DATABASE_URL" envRequired:"true"`743 }744745 func LoadConfig() (*Config, error) {746 // load and validate747 }748 ```749750---751752### 14. Safety, Security, and Performance753754- **Key safety rules (non-negotiable):** 755 - Never ignore errors.756 - Always close resources safely in a `defer`.757 - Validate all user input at the system boundary.758- **For a full catalog:** Point to `references/go-patterns-and-anti-patterns.md`.759- **For Go-specific profiling:** Point to the `perf-optimization` skill.760761---762763### 15. Related Principles764765- Code Idioms and Conventions @code-idioms-and-conventions.md766- Project Structure — Go Backend @references/project-structure.md767- Security Principles @security-principles.md768- Architectural Patterns — Testability-First Design @architectural-pattern.md769- Testing Strategy @testing-strategy.md770- Error Handling Principles @error-handling-principles.md771- Concurrency and Threading Principles @concurrency-and-threading-principles.md772- Logging and Observability Mandate @logging-and-observability-mandate.md773- Logging and Observability Principles @.agents/skills/logging-implementation/SKILL.md774- Dependency Management Principles @dependency-management-principles.md