bateau84/skills

golang-code-style

Go code style conventions — line length, breaking, variable declarations, control flow clarity, and when comments help vs hurt.

View source

How to use

  1. Copy the installation command and review the source package before installing it in your own agent environment.
  2. Check the source document for required tools, credentials and supported hosts.
  3. Describe your input and desired deliverable; review the output against the source material.
npx skills add https://github.com/bateau84/skills --skill golang-code-style

Before you start

  • Installation does not include a model subscription, API allowance or permission to access your files.
  • Repository stars and installation counts describe activity, not an independent quality or security test.
Original skill document

Rendered from the source repository. Headings, examples, code, tables, links, and referenced images are preserved.

Adapted from samber/cc-skills-golang@golang-code-style. Pair with golang-common-practice for verification and cross-reference guidance.

Go Code Style

Style rules that require human judgment — linters handle formatting, this skill handles clarity. For naming see golang-naming skill; for design patterns see golang-design-patterns skill; for struct/interface design see golang-structs-interfaces skill.

"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:

go
// 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."

go
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.

go
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:

go
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:

go
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:

go
// 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

go
// 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:

go
if err := validate(input); err != nil {
    return err
}

Switch Over If-Else Chains

When comparing the same variable multiple times, prefer switch:

go
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. Each parameter is a token the agent must satisfy from the signature alone; exceeding 4 degrades zero-shot usability and signals that an options struct is overdue (see golang-design-patterns skill).
  • Parameter order: context.Context first, 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.
go
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.

go
for _, user := range users {
    process(user)
}

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 can help when it has significant methods; related types that change together may be consolidated. Review cohesion as files grow; roughly 500 lines is a discussion heuristic rather than a mandatory ceiling.
  • Blank imports (_ "pkg") register side effects (init functions). Restricting them to main and 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:

go
func Contains[T comparable](slice []T, target T) bool  // not []any

Philosophy

  • "A little copying is better than a little dependency"
  • Use `slices` and `maps` standard packages; for filter/group-by/chunk, use github.com/samber/lo
  • "Reflection is never clear" — avoid reflect unless 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, cover the applicable independent style concerns (control flow, function design, variable declarations, string handling, code organization) and report evidence-backed findings.

Enforce with Linters

Many rules are enforced automatically: gofmt, gofumpt, goimports, gocritic, revive, wsl_v5. → See the golang-lint skill.

Cross-References

  • → See the golang-naming skill for identifier naming conventions
  • → See the golang-structs-interfaces skill for pointer vs value receivers, interface design
  • → See the golang-design-patterns skill for functional options, builders, constructors
  • → See the golang-lint skill for automated formatting enforcement
  • → See golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines

Related by task

from this repository

More skills

All skills
bateau84
Community

behavioral-spec

Derive bounded, implementation-independent requirements from agreed product intent through goal refinement, coverage lenses, obstacle analysis, provenance tracking, and counterexample checks. Use to select, author, and reconcile Behavioral Requirements (BR), Quality Scenarios (QS), and Obligation Contracts (OC) without expanding scope. Not for concrete API/schema/protocol realization (use architectural-spec) or human-centered stories and scenarios (use user-stories-and-scenarios).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

desktop-ui-design

Desktop GUI design for native and hybrid applications: platform conventions (macOS HIG, Windows Fluent, GNOME HIG), menus, keyboard shortcuts, window management, session persistence, native vs Electron/Tauri trade-offs, and accessibility APIs. Use for Swift/AppKit, C/WinUI, GTK+, or Electron/Tauri/Flutter desktop design. Add web-ui-design for a web app shipped as a desktop wrapper. Not for browser-only interfaces, terminal applications (use tui-design), or command-line tools (use cli-design).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

git-commit-discipline

Small coherent commits, explanatory messages, shared-working-tree discipline, and safe undo/recovery. Use when asked to commit, when a diff mixes concerns, when agents share a working tree, or when undoing or recovering Git changes. Not for content conflicts (use git-conflicts).

installs
1
GitHub stars
0
Updated
Oct 18
bateau84
Community

golang-dependency-injection

google/wire, uber-go/dig, uber-go/fx, samber/do, manual constructor injection, and service containers in Go. Use when designing service architecture, setting up dependency injection, refactoring tightly coupled code, or managing singletons and service factories.

installs
1
GitHub stars
0
Updated
Oct 18