Skills Agentes

Golang Naming

Convenciones de nombres en Go: paquetes, constructores, structs, interfaces, constantes, enums, errores, booleanos, receivers, getters/setters, opciones funcionales, acrónimos y nombres de tests.

Solicitaread edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent
Estrellas
3k

en todo el repo

Actividad
56

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
3

últimos 90 días

Contexto
3.1k tok

188 tok en reposo

Paquete
7 archivos

58 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-naming --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Aplica convenciones de nombres de Go a paquetes, constructores, structs, interfaces, constantes, enums, errores, booleanos, receivers y tests
  • Detecta anti-patrones como stuttering, ALL_CAPS, prefijo Get, o nombres util/helper
  • Sugiere fixes concretos con tabla de referencia rápida y ejemplos correctos/incorrectos

Úsalo cuando

  • Al escribir código Go nuevo
  • Al revisar o refactorizar código existente
  • Al elegir entre alternativas de nombrado (New vs NewTypeName, isConnected vs connected, ErrNotFound vs NotFoundError)
  • Al debatir nombres de paquetes en Go (anti-patrones utils/helpers)

No lo uses cuando

  • Preguntas generales de implementación en Go que no impliquen decisiones de nombrado

Qué lo activa

Di cualquiera de estas frases y el agente debería cargar este skill.

  • ¿Cómo debería nombrar el constructor de este paquete Go?
  • Revisa si estos nombres siguen las convenciones de Go
  • ¿Debo usar isConnected o connected para este campo booleano?
  • ¿ErrNotFound o NotFoundError para este error?

SKILL.md

En inglés

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

Go Naming Conventions

Go favors short, readable names. Capitalization controls visibility — uppercase is exported, lowercase is unexported. All identifiers MUST use MixedCaps, NEVER underscores.

"Clear is better than clever." — Go Proverbs

"Design the architecture, name the components, document the details." — Go Proverbs

To ignore a rule, just add a comment to the code.

Quick Reference

Element Convention Example
Package lowercase, single word, _test suffix OK for test files json, http, tabwriter, http_test
File lowercase, underscores OK user_handler.go
Exported name UpperCamelCase ReadAll, HTTPClient
Unexported lowerCamelCase parseToken, userCount
Interface method name + -er Reader, Closer, Stringer
Struct MixedCaps noun Request, FileHeader
Constant MixedCaps (not ALL_CAPS) MaxRetries, defaultTimeout
Receiver 1-2 letter abbreviation func (s *Server), func (b *Buffer)
Error variable Err prefix ErrNotFound, ErrTimeout
Error type Error suffix PathError, SyntaxError
Constructor New (single type) or NewTypeName (multi-type) ring.New, http.NewRequest
Boolean field is, has, can prefix on fields and methods isReady, IsConnected()
Test function Test + function name TestParseToken
Acronym all caps or all lower URL, HTTPServer, xmlParser
Variant: context WithContext suffix FetchWithContext, QueryContext
Variant: in-place In suffix SortIn(), ReverseIn()
Variant: error Must prefix MustParse(), MustLoadConfig()
Option func With + field name WithPort(), WithLogger()
Enum (iota) type name prefix, zero-value = unknown StatusUnknown at 0, StatusReady
Named return descriptive, for docs only (n int, err error)
Error string lowercase (incl. acronyms), no punctuation "image: unknown format", "invalid id"
Import alias short, only on collision mrand "math/rand", pb "app/proto"
Format func f suffix Errorf, Wrapf, Logf
Test table fields got/expected prefixes input string, expected int

MixedCaps

All Go identifiers MUST use MixedCaps (or mixedCaps). NEVER use underscores in identifiers — the only exceptions are test function subcases (TestFoo_InvalidInput), generated code, and OS/cgo interop. This is load-bearing, not cosmetic — Go's export mechanism relies on capitalization, and tooling assumes MixedCaps throughout.

// ✓ Good
MaxPacketSize
userCount
parseHTTPResponse

// ✗ Bad — these conventions conflict with Go's export mechanism and tooling expectations
MAX_PACKET_SIZE   // C/Python style
max_packet_size   // snake_case
kMaxBufferSize    // Hungarian notation

Avoid Stuttering

Go call sites always include the package name, so repeating it in the identifier wastes the reader's time — http.HTTPClient forces parsing "HTTP" twice. A name MUST NOT repeat information already present in the package name, type name, or surrounding context.

// Good — clean at the call site
http.Client       // not http.HTTPClient
json.Decoder      // not json.JSONDecoder
user.New()        // not user.NewUser()
config.Parse()    // not config.ParseConfig()

// In package sqldb:
type Connection struct{}  // not DBConnection — "db" is already in the package name

// Anti-stutter applies to ALL exported types, not just the primary struct:
// In package dbpool:
type Pool struct{}        // not DBPool
type Status struct{}      // not PoolStatus — callers write dbpool.Status
type Option func(*Pool)   // not PoolOption

Frequently Missed Conventions

These conventions are correct but non-obvious — they are the most common source of naming mistakes:

Constructor naming: When a package exports a single primary type, the constructor is New(), not NewTypeName(). This avoids stuttering — callers write apiclient.New() not apiclient.NewClient(). Use NewTypeName() only when a package has multiple constructible types (like http.NewRequest, http.NewServeMux).

Boolean struct fields: Unexported boolean fields MUST use is/has/can prefix — isConnected, hasPermission, not bare connected or permission. The exported getter keeps the prefix: IsConnected() bool. This reads naturally as a question and distinguishes booleans from other types.

Error strings are fully lowercase — including acronyms. Write "invalid message id" not "invalid message ID", because error strings are often concatenated with other context (fmt.Errorf("parsing token: %w", err)) and mixed case looks wrong mid-sentence. Sentinel errors should include the package name as prefix: errors.New("apiclient: not found").

Enum zero values: Always place an explicit Unknown/Invalid sentinel at iota position 0. A var s Status silently becomes 0 — if that maps to a real state like StatusReady, code can behave as if a status was deliberately chosen when it wasn't.

Subtest names: Table-driven test case names in t.Run() should be fully lowercase descriptive phrases: "valid id", "empty input" — not "valid ID" or "Valid Input".

Detailed Categories

For complete rules, examples, and rationale, see:

  • Packages, Files & Import Aliasing — Package naming (single word, lowercase, no plurals), file naming conventions, import alias patterns (only use on collision to avoid cognitive load), and directory structure.

  • Variables, Booleans, Receivers & Acronyms — Scope-based naming (length matches scope: i for 3-line loops, longer names for package-level), single-letter receiver conventions (s for Server), acronym casing (URL not Url, HTTPServer not HttpServer), and boolean naming patterns (isReady, hasPrefix).

  • Functions, Methods & Options — Getter/setter patterns (Go omits Get so user.Name() reads naturally), constructor conventions (New or NewTypeName), named returns (for documentation only), format function suffixes (Errorf, Wrapf), and functional options (WithPort, WithLogger).

  • Types, Constants & Errors — Interface naming (Reader, Closer suffix with -er), struct naming (nouns, MixedCaps), constants (MixedCaps, not ALL_CAPS), enums (type name prefix like StatusReady), sentinel errors (ErrNotFound variables), error types (PathError suffix), and error message conventions (lowercase, no punctuation).

  • Test Naming — Test function naming (TestFunctionName), table-driven test field conventions (input, expected), test helper naming, and subcase naming patterns.

Common Mistakes

Mistake Fix
ALL_CAPS constants Go reserves casing for visibility, not emphasis — use MixedCaps (MaxRetries)
GetName() getter Go omits Get because user.Name() reads naturally at call sites. But Is/Has/Can prefixes are kept for boolean predicates: IsHealthy() bool not Healthy() bool
Url, Http, Json acronyms Mixed-case acronyms create ambiguity (HttpsUrl — is it Https+Url?). Use all caps or all lower
this or self receiver Go methods are called frequently — use 1-2 letter abbreviation (s for Server) to reduce visual noise
util, helper packages These names say nothing about content — use specific names that describe the abstraction
http.HTTPClient stuttering Package name is always present at call site — http.Client avoids reading "HTTP" twice
user.NewUser() constructor Single primary type uses New()user.New() avoids repeating the type name
connected bool field Bare adjective is ambiguous — use isConnected so the field reads as a true/false question
"invalid message ID" error Error strings must be fully lowercase including acronyms — "invalid message id"
StatusReady at iota 0 Zero value should be a sentinel — StatusUnknown at 0 catches uninitialized values
"not found" error string Sentinel errors should include the package name — "mypackage: not found" identifies the origin
userSlice type-in-name Types encode implementation detail — users describes what it holds, not how
Inconsistent receiver names Switching names across methods of the same type confuses readers — use one name consistently
snake_case identifiers Underscores conflict with Go's MixedCaps convention and tooling expectations — use mixedCaps
Long names for short scopes Name length should match scope — i is fine for a 3-line loop, userIndex is noise
Naming constants by value Values change, roles don't — DefaultPort survives a port change, Port8080 doesn't
FetchCtx() context variant WithContext is the standard Go suffix — FetchWithContext() is instantly recognizable
sort() in-place but no In Readers assume functions return new values. SortIn() signals mutation
parse() panicking on error MustParse() warns callers that failure panics — surprises belong in the name
Mixing With*, Set*, Use* Consistency across the codebase — With* is the Go convention for functional options
Plural package names Go convention is singular (net/url not net/urls) — keeps import paths consistent
Wrapf without f suffix The f suffix signals format-string semantics — Wrapf, Errorf tell callers to pass format args
Unnecessary import aliases Aliases add cognitive load. Only alias on collision — mrand "math/rand"
Inconsistent concept names Using user/account/person for the same concept forces readers to track synonyms — pick one name

Applying these fixes means renaming existing identifiers — → See samber/cc-skills-golang@golang-gopls skill to do it safely: its rename updates every call site across the workspace and refuses a rename that would break interface satisfaction, which a grep/sed or manual Edit-based rename silently misses.

Enforce with Linters

Many naming convention issues are caught automatically by linters: revive, predeclared, misspell, errname. See samber/cc-skills-golang@golang-lint skill for configuration and usage.

Cross-References

  • → See samber/cc-skills-golang@golang-code-style skill for broader formatting and style decisions
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface naming depth and receiver design
  • → See samber/cc-skills-golang@golang-lint skill for automated enforcement (revive, predeclared, misspell, errname)
  • → See samber/cc-skills-golang@golang-gopls skill for safe rename when applying a naming fix
  • → See samber/cc-skills-golang@golang-refactoring skill for how to apply a rename safely at scale (gopls Rename/Inline, blast-radius mapping, staged PR workflow) once you've decided what to rename identifiers to

Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

Archivos

7 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

Antes de instalar

Pensado para proyectos que usan Golang, con el binario go disponible.

Detalles

Creador
samber
Licencia
MIT
Recursos incluidos
referencias
Código fuente
Ver SKILL.md

Etiquetas

Más de samber/cc-skills-golang

Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

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.

Costo de contexto al activarse
1.8k tok
Tamaño del paquete
5 archivos
Última actualización
hace 3 días
herramientas desarrollo

Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

Costo de contexto al activarse
3.3k tok
Tamaño del paquete
10 archivos
Última actualización
hace 28 días
testing qa

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.

Costo de contexto al activarse
3.8k tok
Tamaño del paquete
4 archivos
Última actualización
hace 20 días
herramientas desarrollo

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.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
9 archivos
Última actualización
el mes pasado
herramientas desarrollo

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.

Costo de contexto al activarse
4.4k tok
Tamaño del paquete
6 archivos
Última actualización
el mes pasado
testing qa

Inyección de dependencias en Golang con samber/do: contenedores de servicios, gestión de ciclo de vida, scopes, health checks, apagado ordenado y organización en módulos.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
4 archivos
Última actualización
hace 22 días
herramientas desarrollo

Skills relacionados

Desarrollo de aplicaciones CLI en Go: estructura de comandos, flags, configuración por capas, versión embebida, exit codes, señales, completions y testing con cobra, viper o urfave/cli.

Costo de contexto al activarse
2.6k tok
Tamaño del paquete
14 archivos
Última actualización
hace 3 meses
herramientas desarrollo

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.

Costo de contexto al activarse
2.5k tok
Tamaño del paquete
3 archivos
Última actualización
el mes pasado
herramientas desarrollo

Patrones de concurrencia en Go: úsalo al escribir o revisar código concurrente con goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools o pipelines fan-out/fan-in.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
5 archivos
Última actualización
el mes pasado
herramientas desarrollo