bysamber· 66 skills
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See samber/cc-skills-golang@golang-naming skill), linter configuration (→ See samber/cc-skills-golang@golang-lint skill), or doc comments (→ See samber/cc-skills-golang@golang-documentation skill).
$npx -y skills add samber/cc-skills-golang --skill golang-code-styleInstalls into the current project.
Run `npx skills use "https://github.com/samber/cc-skills-golang" --skill "samber/cc-skills-golang/golang-code-style"` and follow the generated skill instructions now. Read its complete output, redirecting it to a temporary file first if necessary. Resolve relative paths from the supporting-files directory it provides.
Use the skills in "https://github.com/samber/cc-skills-golang" that are relevant to the current task. Run `npx skills add "https://github.com/samber/cc-skills-golang"` and select the relevant skills, then follow their instructions.
| 1 | **Orchestration mode:** Use `ultracode` when reviewing code style across a large codebase — orchestrate the sub-agents described in the "Parallelizing Code Style Reviews" section, each covering an independent style concern, and merge their findings. |
| 2 | |
| 3 | > **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-code-style` skill takes precedence. |
| 4 | |
| 5 | # Go Code Style |
| 6 | |
| 7 | 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. |
| 8 | |
| 9 | > "Clear is better than clever." — Go Proverbs |
| 10 | |
| 11 | When ignoring a rule, add a comment to the code. |
| 12 | |
| 13 | ## Line Length & Breaking |
| 14 | |
| 15 | 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: |
| 16 | |
| 17 | ```go |
| 18 | // Good — each argument on its own line, closing paren separate |
| 19 | mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) { |
| 20 | handleUsers( |
| 21 | w, |
| 22 | r, |
| 23 | serviceName, |
| 24 | cfg, |
| 25 | logger, |
| 26 | authMiddleware, |
| 27 | ) |
| 28 | }) |
| 29 | ``` |
| 30 | |
| 31 | 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. |
| 32 | |
| 33 | ## Variable Declarations |
| 34 | |
| 35 | SHOULD use `:=` for non-zero values, `var` for zero-value initialization. The form signals intent: `var` means "this starts at zero." |
| 36 | |
| 37 | ```go |
| 38 | var count int // zero value, set later |
| 39 | name := "default" // non-zero, := is appropriate |
| 40 | var buf bytes.Buffer // zero value is ready to use |
| 41 | ``` |
| 42 | |
| 43 | ### Slice & Map Initialization |
| 44 | |
| 45 | 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. |
| 46 | |
| 47 | ```go |
| 48 | users := []User{} // always initialized |
| 49 | m := map[string]int{} // always initialized |
| 50 | users := make([]User, 0, len(ids)) // preallocate when capacity is known |
| 51 | m := make(map[string]int, len(items)) // preallocate when size is known |
| 52 | ``` |
| 53 | |
| 54 | Do not preallocate speculatively — `make([]T, 0, 1000)` wastes memory when the common case is 10 items. |
| 55 | |
| 56 | ### Composite Literals |
| 57 | |
| 58 | Composite literals MUST use field names — positional fields break when the type adds or reorders fields: |
| 59 | |
| 60 | ```go |
| 61 | srv := &http.Server{ |
| 62 | Addr: ":8080", |
| 63 | ReadTimeout: 5 * time.Second, |
| 64 | WriteTimeout: 10 * time.Second, |
| 65 | } |
| 66 | ``` |
| 67 | |
| 68 | ## Control Flow |
| 69 | |
| 70 | ### Reduce Nesting |
| 71 | |
| 72 | Errors and edge cases MUST be handled first (early return). Keep the happy path at minimal indentation: |
| 73 | |
| 74 | ```go |
| 75 | func process(data []byte) (*Result, error) { |
| 76 | if len(data) == 0 { |
| 77 | return nil, errors.New("empty data") |
| 78 | } |
| 79 | |
| 80 | parsed, err := parse(data) |
| 81 | if err != nil { |
| 82 | return nil, fmt.Errorf("parsing: %w", err) |
| 83 | } |
| 84 | |
| 85 | return transform(parsed), nil |
| 86 | } |
| 87 | ``` |
| 88 | |
| 89 | ### Eliminate Unnecessary `else` |
| 90 | |
| 91 | 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`: |
| 92 | |
| 93 | ```go |
| 94 | // Good — default-then-override with switch (cleanest for mutually exclusive overrides) |
| 95 | level := slog.LevelInfo |
| 96 | switch { |
| 97 | case debug: |
| 98 | level = slog.LevelDebug |
| 99 | case verbose: |
| 100 | level = slog.LevelWarn |
| 101 | } |
| 102 | |
| 103 | // Bad — else-if chain hides that there's a default |
| 104 | if debug { |
| 105 | level = slog.LevelDebug |
| 106 | } else if verbose { |
| 107 | level = slog.LevelWarn |
| 108 | } else { |
| 109 | level = slog.LevelInfo |
| 110 | } |
| 111 | ``` |
| 112 | |
| 113 | ### Complex Conditions & Init Scope |
| 114 | |
| 115 | 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](./references/details.md) |
| 116 | |
| 117 | ```go |
| 118 | // Good — named booleans make intent clear |
| 119 | isAdmin := user.Role == RoleAdmin |
| 120 | isOwner := resource.OwnerID == user.ID |
| 121 | isPublicVerified := resource.IsPublic && user.IsVerified |
| 122 | if isAdmin || isOwner || isPublicVerified || permissions.Contains(PermOverride) { |
| 123 | allow() |
| 124 | } |
| 125 | ``` |
| 126 | |
| 127 | Scope variables to `if` blocks when only needed for the check: |
| 128 | |
| 129 | ```go |
| 130 | if err := validate(input); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | ``` |
| 134 | |
| 135 | ### Switch Over If-Else Chains |
| 136 | |
| 137 | When comparing the same variable multiple times, prefer `switch`: |
| 138 | |
| 139 | ```go |
| 140 | switch status { |
| 141 | case StatusActive: |
| 142 | activate() |
| 143 | case StatusInactive: |
| 144 | deactivate() |
| 145 | default: |
| 146 | panic(fmt.Sprintf("unexpected status: %d", status)) |
| 147 | } |
| 148 | ``` |
| 149 | |
| 150 | ## Function Design |
| 151 | |
| 152 | - Functions SHOULD be **short and focused** — one function, one job. |
| 153 | - Functions SHOULD have **≤4 parameters**. Beyond that, use an options struct (see `samber/cc-skills-golang@golang-design-patterns` skill). |
| 154 | - **Parameter order**: `context.Context` first, then inputs, then output destinations. |
| 155 | - 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. |
| 156 | |
| 157 | ```go |
| 158 | func FetchUser(ctx context.Context, id string) (*User, error) |
| 159 | func SendEmail(ctx context.Context, msg EmailMessage) error // grouped into struct |
| 160 | ``` |
| 161 | |
| 162 | ### Prefer `range` for Iteration |
| 163 | |
| 164 | SHOULD use `range` over index-based loops. Use `range n` (Go 1.22+) for simple counting. |
| 165 | |
| 166 | ```go |
| 167 | for _, user := range users { |
| 168 | process(user) |
| 169 | } |
| 170 | ``` |
| 171 | |
| 172 | ## Value vs Pointer Arguments |
| 173 | |
| 174 | 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](./references/details.md) |
| 175 | |
| 176 | ## Code Organization Within Files |
| 177 | |
| 178 | - **Group related declarations**: type, constructor, methods together |
| 179 | - **Order**: package doc, imports, constants, types, constructors, methods, helpers |
| 180 | - **One primary type per file** when it has significant methods |
| 181 | - **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 |
| 182 | - **Dot imports** pollute the namespace and make it impossible to tell where a name comes from — never use in library code |
| 183 | - **Unexport aggressively** — you can always export later; unexporting is a breaking change. → See `samber/cc-skills-golang@golang-gopls` skill to unexport safely — its rename updates every call site atomically and refuses the change when lowercasing a method would break interface satisfaction, a breakage grep/sed silently ships. |
| 184 | |
| 185 | ## String Handling |
| 186 | |
| 187 | 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. |
| 188 | |
| 189 | ## Type Conversions |
| 190 | |
| 191 | Prefer explicit, narrow conversions. Use generics over `any` when a concrete type will do: |
| 192 | |
| 193 | ```go |
| 194 | func Contains[T comparable](slice []T, target T) bool // not []any |
| 195 | ``` |
| 196 | |
| 197 | ## Philosophy |
| 198 | |
| 199 | - **"A little copying is better than a little dependency"** |
| 200 | - **Use `slices` and `maps` standard packages**; for filter/group-by/chunk, use `github.com/samber/lo` |
| 201 | - **"Reflection is never clear"** — avoid `reflect` unless necessary |
| 202 | - **Don't abstract prematurely** — extract when the pattern is stable |
| 203 | - **Minimize public surface** — every exported name is a commitment |
| 204 | |
| 205 | ## Parallelizing Code Style Reviews |
| 206 | |
| 207 | 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). |
| 208 | |
| 209 | ## Enforce with Linters |
| 210 | |
| 211 | Many rules are enforced automatically: `gofmt`, `gofumpt`, `goimports`, `gocritic`, `revive`, `wsl_v5`. → See the `samber/cc-skills-golang@golang-lint` skill. |
| 212 | |
| 213 | ## Cross-References |
| 214 | |
| 215 | - → See the `samber/cc-skills-golang@golang-naming` skill for identifier naming conventions |
| 216 | - → See the `samber/cc-skills-golang@golang-structs-interfaces` skill for pointer vs value receivers, interface design |
| 217 | - → See the `samber/cc-skills-golang@golang-design-patterns` skill for functional options, builders, constructors |
| 218 | - → See the `samber/cc-skills-golang@golang-lint` skill for automated formatting enforcement |
| 219 | - → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines |
| 220 | - → See `samber/cc-skills-golang@golang-refactoring` skill for mechanically applying guard-clause conversion, function extraction, and options-struct migration safely across many call sites once a review surfaces violations at scale |