Golang Style Guide β
Per-language style guide for Go. Shared rules: the Coding Style Guide. Requirement levels follow RFC 2119; tags π / π are defined there.
1. Formatting π β
- Code MUST be formatted with
gofmt. Agofmtdiff MUST block review. - Code MUST follow Effective Go and Go Code Review Comments.
2. Error Handling π β
Functions MUST return
error; callers MUST handle it at the call site:gov, err := doThing() if err != nil { return fmt.Errorf("doThing: %w", err) }Errors MUST be wrapped with
%wto add context. Errors MUST NOT be discarded with_.panicMUST NOT be used for normal error handling.panicMAY be used for unrecoverable bugs or program init, but MUST NOT cross a package boundary β convert it to anerrorfirst.
β panic used for an expected failure crashes the caller:
func mustLoad(id string) User {
u, err := db.Load(id)
if err != nil {
panic(err)
}
return u
}β
The failure is returned as an error the caller must handle:
func load(id string) (User, error) {
u, err := db.Load(id)
if err != nil {
return User{}, fmt.Errorf("load %s: %w", id, err)
}
return u, nil
}Rationale: errors-as-values is mandated by Go (Go Code Review Comments, Uber, Effective Go). Go's error return is the idiomatic Result (Either).
3. Mutation π (scoped) β
- Mutable global state MUST be avoided; use dependency injection.
- Slices and maps MUST be copied at API boundaries to avoid aliasing.
Note: Go idiom permits local mutation; the constraint is on globals and boundary aliasing.
4. Interfaces π β
- Interfaces SHOULD be small and defined by the consumer. An interface with a single implementation MUST NOT be exported.
Note: Go idiom is "accept interfaces, return structs" with consumer-defined interfaces (Go Code Review Comments, Effective Go).
References β
- Go Code Review Comments β https://go.dev/wiki/CodeReviewComments
- Effective Go β https://go.dev/doc/effective_go
- Go: Defer, Panic, and Recover β https://go.dev/blog/defer-panic-and-recover
- Go Wiki: PanicAndRecover β https://go.dev/wiki/PanicAndRecover
- Uber Go Style Guide β https://github.com/uber-go/guide/blob/master/style.md