golang-code-style
Golang code style, formatting and conventions. Use when writing code, reviewing style, configuring linters, writing comments, or establishing project standards.
- License 许可
- MIT
- 最近更新
- 2026-04-04
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- golang-code-style
- license
- MIT
- metadata
- { "author": "samber", "version": "1.0", "openclaw": { "emoji": "?", "install": [], "homepage": "https://github.com/paulohgodinho/skills", "requires": { "bins": [ "go" ] } } }
- description
- Golang code style, formatting and conventions. Use when writing code, reviewing style, configuring linters, writing comments, or establishing project standards.
- allowed-tools
- Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent
- compatibility
- Designed for Claude Code or similar AI coding agents, and for projects using Golang.
- user-invocable
- false
02 资源文件 2
- 参考文档evals/evals.json31.8 KB
- 参考文档references/details.md2.7 KB
03 SKILL.md 正文
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-code-styleskill takes precedence.
Go Code Style
Style rules that require human judgment — linters handle formatting, this skill handles clarity. For naming see golang-naming; for design patterns see golang-design-patterns; for struct/interface design see golang-structs-interfaces.
"Clear is better than clever." — Go Proverbs
When ignoring a rule, add a comment to the code.
Line Length & Breaking
No rigid line limit, but lines beyond ~120 characters MUST be broken. Break at semantic boundaries, not arbitrary column counts. Function calls with 4+ arguments MUST use one argument per line — even when the prompt asks for single-line code:
// Good — each argument on its own line, closing paren separate
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
handleUsers(
w,
r,
serviceName,
cfg,
logger,
authMiddleware,
)
})
When a function signature is too long, the real fix is often fewer parameters (use an options struct) rather than better line wrapping. For multi-line signatures, put each parameter on its own line.
Variable Declarations
SHOULD use := for non-zero values, var for zero-value initialization. The form signals intent: var means "this starts at zero."
var count int // zero value, set later
name := "default" // non-zero, := is appropriate
var buf bytes.Buffer // zero value is ready to use
Slice & Map Initialization
Slices and maps MUST be initialized explicitly, never nil. Nil maps panic on write; nil slices serialize to null in JSON (vs [] for empty slices), surprising API consumers.
users := []User{} // always initialized
m := map[string]int{} // always initialized
users := make([]User, 0, len(ids)) // preallocate when capacity is known
m := make(map[string]int, len(items)) // preallocate when size is known
Do not preallocate speculatively — make([]T, 0, 1000) wastes memory when the common case is 10 items.
Composite Literals
Composite literals MUST use field names — positional fields break when the type adds or reorders fields:
srv := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
Control Flow
Reduce Nesting
Errors and edge cases MUST be handled first (early return). Keep the happy path at minimal indentation:
func process(data []byte) (*Result, error) {
if len(data) == 0 {
return nil, errors.New("empty data")
}
parsed, err := parse(data)
if err != nil {
return nil, fmt.Errorf("parsing: %w", err)
}
return transform(parsed), nil
}
Eliminate Unnecessary else
When the if body ends with return/break/continue, the else MUST be dropped. Use default-then-override for simple assignments — assign a default, then override with independent conditions or a switch:
// Good — default-then-override with switch (cleanest for mutually exclusive overrides)
level := slog.LevelInfo
switch {
case debug:
level = slog.LevelDebug
case verbose:
level = slog.LevelWarn
}
// Bad — else-if chain hides that there's a default
if debug {
level = slog.LevelDebug
} else if verbose {
level = slog.LevelWarn
} else {
level = slog.LevelInfo
}
Complex Conditions & Init Scope
When an if condition has 3+ operands, MUST extract into named booleans — a wall of || is unreadable and hides business logic. Keep expensive checks inline for short-circuit benefit. Details
// Good — named booleans make intent clear
isAdmin := user.Role == RoleAdmin
isOwner := resource.OwnerID == user.ID
isPublicVerified := resource.IsPublic && user.IsVerified
if isAdmin || isOwner || isPublicVerified || permissions.Contains(PermOverride) {
allow()
}
Scope variables to if blocks when only needed for the check:
if err := validate(input); err != nil {
return err
}
Switch Over If-Else Chains
When comparing the same variable multiple times, prefer switch:
switch status {
case StatusActive:
activate()
case StatusInactive:
deactivate()
default:
panic(fmt.Sprintf("unexpected status: %d", status))
}
Function Design
- Functions SHOULD be short and focused — one function, one job.
- Functions SHOULD have ≤4 parameters. Beyond that, use an options struct (see golang-design-patterns).
- Parameter order:
context.Contextfirst, then inputs, then output destinations. - Naked returns help in very short functions (1-3 lines) where return values are obvious, but become confusing when readers must scroll to find what's returned — name returns explicitly in longer functions.
func FetchUser(ctx context.Context, id string) (*User, error)
func SendEmail(ctx context.Context, msg EmailMessage) error // grouped into struct
Prefer range for Iteration
SHOULD use range over index-based loops. Use range n (Go 1.22+) for simple counting.
for _, user := range users {
process(user)
}
Comments
Comments are a last resort. When code requires a comment to be understood, the first instinct MUST be to rename, restructure, or simplify — not to add a comment. A comment that restates what a name already expresses is noise: it adds clutter and drifts out of sync with the code.
Never Comment These
// Bad — comment just repeats the function name
// getUserByID returns a user by their ID
func getUserByID(ctx context.Context, id string) (*User, error) { ... }
// Bad — comment repeats the variable assignment
// isActive checks whether the user is active
isActive := user.Status == StatusActive
// Bad — comment restates the loop count
// Retry the request up to 3 times
for range 3 { ... }
Only Comment These
The only legitimate reasons to add a comment are:
- Magic numbers / hardcoded values — explain why the value is what it is
- Non-obvious logic — explain why, not what
- Intentional no-ops — prevent the next reader from thinking it's a bug
TODO/FIXME— track known issues or planned work
// Good — magic number with rationale
const gcGracePeriod = 2 * time.Minute // GC finalizers can delay ~1min; double for safety
// Good — non-obvious invariant
// Subtract 1: the token bucket counts from 0, so capacity N gives N+1 slots;
// correct here to match the documented API contract.
available := bucket.Cap() - 1
// Good — intentional no-op
select {
case <-done:
return
default:
// not ready yet — continue
}
// Good — tracking known work
// TODO: replace with streaming once the upstream API supports it
data, err := io.ReadAll(r)
// FIXME: this silently drops the error on context cancellation
_ = client.Flush()
Godoc Exception
Exported symbols MAY have a godoc comment so that go doc and IDEs work correctly. Even then, prefer a name so clear that the godoc is a single short sentence — not a paragraph explaining what the code already shows.
// Good — godoc adds genuinely useful context beyond the name
// ParseDuration extends time.ParseDuration to support 'd' (day) and 'w' (week) units.
func ParseDuration(s string) (time.Duration, error) { ... }
// Bad — godoc just echoes the name
// GetUser retrieves a user.
func GetUser(ctx context.Context, id string) (*User, error) { ... }
Rule of Thumb
Before writing a comment, ask: can I express this with a better name or a helper function?
// Bad — comment compensates for a cryptic condition
// skip unverified users created before the migration cutoff
if user.DeletedAt != nil || (!user.IsVerified && user.CreatedAt.Before(cutoff)) {
// Good — extract into a named boolean
shouldSkip := user.DeletedAt != nil || (!user.IsVerified && user.CreatedAt.Before(cutoff))
if shouldSkip {
Value vs Pointer Arguments
Pass small types (string, int, bool, time.Time) by value. Use pointers when mutating, for large structs (~128+ bytes), or when nil is meaningful. Details
Code Organization Within Files
- Group related declarations: type, constructor, methods together
- Order: package doc, imports, constants, types, constructors, methods, helpers
- One primary type per file when it has significant methods
- Blank imports (
_ "pkg") register side effects (init functions). Restricting them tomainand test packages makes side effects visible at the application root, not hidden in library code - Dot imports pollute the namespace and make it impossible to tell where a name comes from — never use in library code
- Unexport aggressively — you can always export later; unexporting is a breaking change
String Handling
Use strconv for simple conversions (faster), fmt.Sprintf for complex formatting. Use %q in error messages to make string boundaries visible. Use strings.Builder for loops, + for simple concatenation.
Type Conversions
Prefer explicit, narrow conversions. Use generics over any when a concrete type will do:
func Contains[T comparable](slice []T, target T) bool // not []any
Philosophy
- "A little copying is better than a little dependency"
- Use
slicesandmapsstandard packages - "Reflection is never clear" — avoid
reflectunless necessary - Don't abstract prematurely — extract when the pattern is stable
- Minimize public surface — every exported name is a commitment
Parallelizing Code Style Reviews
When reviewing code style across a large codebase, use up to 5 parallel sub-agents (via the Agent tool), each targeting an independent style concern (e.g. control flow, function design, variable declarations, string handling, code organization).
Enforce with Linters
Many rules are enforced automatically: gofmt, gofumpt, goimports, gocritic, revive, wsl_v5. → See the golang-linter skill.
Cross-References
- → See golang-naming for identifier naming conventions
- → See golang-structs-interfaces for pointer vs value receivers, interface design
- → See golang-design-patterns for functional options, builders, constructors
- → See golang-linter for automated formatting enforcement
04 同仓库更多 Skills
golang-structs-interfaces
Golang struct and interface design patterns — composition, embedding, type assertions, type switches, interface segregation, dependency injection via interfaces, struct field tags, and pointer vs value receivers. Use this skill when designing Go types, defining or implementing interfaces, embedding structs or interfaces, writing type assertions or type switches, adding struct field tags for JSON/YAML/DB serialization, or choosing between pointer and value receivers. Also use when the user asks about "accept interfaces, return structs", compile-time interface checks, or composing small interfaces into larger ones.
golang-project-layout
Provides a guide for setting up Golang project layouts and workspaces. Use this whenever starting a new Go project, organizing an existing codebase, setting up a monorepo with multiple packages, creating CLI tools with multiple main packages, or deciding on directory structure. Apply this for any Go project initialization or restructuring work.
golang-naming
Go (Golang) naming conventions — covers packages, constructors, structs, interfaces, constants, enums, errors, booleans, receivers, getters/setters, functional options, acronyms, test functions, and subtest names. Use this skill when writing new Go code, reviewing or refactoring, choosing between naming alternatives (New vs NewTypeName, isConnected vs connected, ErrNotFound vs NotFoundError, StatusReady vs StatusUnknown at iota 0), debating Go package names (utils/helpers anti-patterns), or asking about Go naming best practices. Also trigger when the user mentions MixedCaps vs snake_case, ALL_CAPS constants, Get-prefix on getters, or error string casing. Do NOT use for general Go implementation questions that don't involve naming decisions.
golang-lint
Provides linting best practices and golangci-lint configuration for Go projects. Covers running linters, configuring .golangci.yml, suppressing warnings with nolint directives, interpreting lint output, and managing linter settings. Use this skill whenever the user runs linters, configures golangci-lint, asks about lint warnings or suppressions, sets up code quality tooling, or asks which linters to enable for a Go project. Also use when the user mentions golangci-lint, go vet, staticcheck, revive, or any Go linting tool.
golang-design-patterns
Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, and streaming. Apply when designing Go APIs, structuring applications, choosing between patterns, making design decisions, architectural choices, or production hardening.
golang-dependency-injection
Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go.