| description | Go idioms and conventions for .go files | |
|---|---|---|
| globs |
|
- Check errors immediately after every call that returns one. Never defer error checks.
- Return errors to the caller. Do not
panicfor recoverable errors. - Wrap errors with context:
fmt.Errorf("loading config: %w", err). - Define custom error types using
errors.Newor a struct implementing theerrorinterface.
- Pass
context.Contextas the first parameter in functions that do I/O or may be cancelled. - Keep function signatures short. If a function needs more than four or five parameters, use an options struct.
- Use short variable names in small scopes (
i,v,err,n). - Use descriptive names for package-level and exported identifiers.
- Prefer
:=for local variable declarations. Usevaronly when zero-value initialization is intentional or the type must be explicit.
- Define interfaces at the point of use (in the package that consumes them), not in the package that implements them.
- Keep interfaces small - one to three methods is ideal.
- Use interfaces to make code testable by allowing fake/stub implementations.
- Use table-driven tests with
[]struct{ name, input, want }slices. - Name subtests with
t.Run(tc.name, ...)so failures are easy to identify. - Prefer the standard
testingpackage. Addtestify/assertonly when it reduces significant boilerplate.
- Follow the standard Go project layout:
cmd/,internal/,pkg/. - Keep
mainpackages incmd/<binary-name>/main.go. - Put packages that must not be imported externally under
internal/.
- Use channels to communicate between goroutines. Do not share memory without a mutex.
- Always specify goroutine lifecycle: who starts it, who waits for it, and how it exits.