← Back to Skills Marketplace
samber

Golang Code Style

by Samuel Berthe · GitHub ↗ · v1.1.1 · MIT-0
cross-platform ✓ Security Clean
287
Downloads
0
Stars
0
Active Installs
2
Versions
Install in OpenClaw
/install golang-code-style
Description
Golang code style, formatting and conventions. Use when writing code, reviewing style, configuring linters, writing comments, or establishing project standards.
README (SKILL.md)

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-code-style skill takes precedence.

Go Code Style

Style rules that require human judgment — linters handle formatting, this skill handles clarity. For naming see samber/cc-skills-golang@golang-naming skill; for design patterns see samber/cc-skills-golang@golang-design-patterns skill; for struct/interface design see samber/cc-skills-golang@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:

// 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 samber/cc-skills-golang@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.
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)
}

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

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, 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 samber/cc-skills-golang@golang-lint skill.

Cross-References

  • → See the samber/cc-skills-golang@golang-naming skill for identifier naming conventions
  • → See the samber/cc-skills-golang@golang-structs-interfaces skill for pointer vs value receivers, interface design
  • → See the samber/cc-skills-golang@golang-design-patterns skill for functional options, builders, constructors
  • → See the samber/cc-skills-golang@golang-lint skill for automated formatting enforcement
  • → See samber/cc-skills-golang@golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines
Usage Guidance
This skill is largely low-risk: it's an instruction-only Go style guide and does not request secrets or install code. Note that the skill metadata and allowed-tools indicate the agent may run 'go' and linters (e.g., golangci-lint, git) against your workspace — if you don't want the agent to execute formatting/linting commands locally, restrict tool access or review the agent's permissions before enabling the skill. Also confirm you trust the source/homepage and the versions of any tools the agent will use, since the skill itself doesn't pin or install those tools.
Capability Analysis
Type: OpenClaw Skill Name: golang-code-style Version: 1.1.1 The skill bundle provides standard Go coding style guidelines and best practices for an AI agent. The instructions in SKILL.md and references/details.md focus on code clarity, formatting, and performance (e.g., pointer vs. value arguments). The requested tool permissions, including restricted Bash access for 'go', 'golangci-lint', and 'git', are appropriate for the stated purpose of code review and formatting.
Capability Assessment
Purpose & Capability
Name/description match the content: the SKILL.md is a Go code-style guide. The metadata declares the 'go' binary as required — reasonable if the agent will run go tools (gofmt/govet/etc.), but not strictly necessary for a purely prose style guide. This is a minor mismatch worth noting.
Instruction Scope
Instructions are style guidelines and examples only. The SKILL.md does not direct the agent to read unrelated files, exfiltrate data, call external endpoints, or access environment variables beyond the declared requirements.
Install Mechanism
No install spec and no code files — instruction-only. Nothing will be downloaded or written to disk by the skill itself.
Credentials
The skill declares no environment variables, secrets, or config paths. It only lists a required binary ('go'), which is proportionate to its possible need to run Go tooling.
Persistence & Privilege
always:false and no special privileges requested. The skill can be invoked autonomously by the agent (platform default) but does not request permanent presence or to modify other skills/config.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install golang-code-style
  3. After installation, invoke the skill by name or use /golang-code-style
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.1.1
- Removed the file `evals/evals.json`. - Minor edit to SKILL.md: rephrased the instruction on ignoring rules to "When ignoring a rule, add a comment to the code." - No changes to functionality or core style guidance.
v1.1.0
- Expanded and clarified Go code style rules, focusing on structure, naming, and control flow. - Added detailed guidelines for line breaking, function argument formatting, and composite literals. - Emphasized explicit initialization for slices and maps to avoid bugs. - Defined clearer standards for reducing nesting, handling errors early, and simplifying conditional logic. - Included recommendations for iteration, function design, code organization, and parallelizing style reviews. - Updated compatibility and metadata for improved integration with code agents.
Metadata
Slug golang-code-style
Version 1.1.1
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 2
Frequently Asked Questions

What is Golang Code Style?

Golang code style, formatting and conventions. Use when writing code, reviewing style, configuring linters, writing comments, or establishing project standards. It is an AI Agent Skill for Claude Code / OpenClaw, with 287 downloads so far.

How do I install Golang Code Style?

Run "/install golang-code-style" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Golang Code Style free?

Yes, Golang Code Style is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does Golang Code Style support?

Golang Code Style is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Golang Code Style?

It is built and maintained by Samuel Berthe (@samber); the current version is v1.1.1.

💬 Comments