# Golang Code Style > Convenciones de estilo en Golang: longitud y corte de líneas, declaración de variables, claridad del control de flujo y cuándo los comentarios ayudan u estorban. Fuente: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-code-style Markdown: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-code-style.md Repositorio: https://github.com/samber/cc-skills-golang Autor: samber Licencia: MIT Actualizado: el mes pasado Coste de contexto: 121 tok instalada, 2.5k tok al activarse, 12.1k tok con todos los archivos del bundle Bundle: 3 archivos, 47 KB Permisos que pide: read edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent claude-code # Cursor npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent cursor # Codex npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent codex # Gemini CLI npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent gemini # Windsurf npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent windsurf # Cline npx -y skills add samber/cc-skills-golang --skill golang-code-style --agent cline ``` ## Qué hace - Aplica reglas de estilo Go sobre longitud de línea, declaraciones de variables, control de flujo y diseño de funciones - Exige inicialización explícita de slices/mapas y literales compuestos con nombres de campo - Fuerza retorno temprano, eliminación de else innecesarios y extracción de condiciones complejas en booleanos nombrados - Orquesta sub-agentes en paralelo para revisar estilo en bases de código grandes ## Cuándo usarla - Al escribir o revisar código Go - Al preguntar sobre estilo o claridad del código - Al establecer estándares de codificación de un proyecto - Al revisar estilo de código en una base de código grande (modo ultracode) ## Cuándo no - Para convenciones de nombres, usa el skill golang-naming - Para configuración de linters, usa el skill golang-lint - Para comentarios de documentación, usa el skill golang-documentation ## Qué la activa - "Revisa el estilo de este código Go" - "¿Cómo debería estructurar esta función con muchos parámetros?" - "Establece las normas de estilo de código para este proyecto Go" - "Refactoriza este if-else para que sea más claro" ## Antes de instalar - Requiere el binario go y está pensado para agentes de codificación tipo Claude Code en proyectos Golang. ## Archivos - SKILL.md — 10 KB - evals/evals.json — 35 KB - references/details.md — 3 KB ## SKILL.md Reproducido tal cual desde samber/cc-skills-golang bajo MIT. Esta sección es el documento original y está en inglés. **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. > **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: ```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](./references/details.md) ```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**. 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. ```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](./references/details.md) ## 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. → 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. ## 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, 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 - → 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 ## Dónde encaja - Categoría: [Herramientas para desarrolladores](https://skillsagentes.com/categorias/herramientas-desarrollo.md) — Skills que cambian cómo tu agente escribe, revisa y despliega código. - Creador: [samber](https://skillsagentes.com/creators/samber.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Golang Lint](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint.md): Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters. - [Golang How To](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-how-to.md): Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Performance](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-performance.md): Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron. ## Skills relacionadas - [Golang Samber Hot](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-hot.md): Caché en memoria en Golang con samber/hot: algoritmos de expulsión (LRU, LFU, TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, loaders, sharding y métricas Prometheus. - [Golang Samber Lo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-lo.md): Helpers funcionales para Go con samber/lo: 500+ funciones genéricas type-safe para slices, maps, canales, strings, math, tuplas y concurrencia. - [Golang Samber Mo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-mo.md): Tipos monádicos para Golang con samber/mo — Option, Result, Either, Future, IO, Task y State para valores nulos seguros, manejo de errores y composición funcional. - [Golang Samber Slog](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-slog.md): Extensiones de logging estructurado para Go con paquetes samber/slog-****: pipelines multi-handler, sampling, formateo de atributos, middleware HTTP y enrutamiento a backends como Datadog, Sentry o Loki. - [Golang Spf13 Viper](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-spf13-viper.md): Librería de configuración en Go con spf13/viper: precedencia en capas (flag > env > archivo > KV > default), BindPFlag, AutomaticEnv, Unmarshal con mapstructure, Sub, WatchConfig y aislamiento en tests. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)