go-data-structures
Acerca de
Esta habilidad ofrece mejores prácticas para las estructuras de datos fundamentales de Go: slices, maps y arrays, abarcando errores comunes como slices nil versus vacíos, aliasing, preasignación e iteración de maps. Úsala para preguntas sobre semántica de slices, implementación de conjuntos o elección entre estructuras de datos. Excluye explícitamente concurrencia, perfilado de rendimiento y temas de diseño genérico, los cuales están cubiertos por otras habilidades.
Instalación rápida
Claude Code
Recomendadonpx skills add eduardo-sl/go-agent-skills -a claude-code/plugin add https://github.com/eduardo-sl/go-agent-skillsgit clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-data-structuresCopia y pega este comando en Claude Code para instalar esta habilidad
Documentación
Go Data Structures
Slices and maps look simple and hide the sharpest edges in the language. These rules prevent the aliasing, nil, and iteration bugs that survive code review.
1. Nil Slice vs Empty Slice
var a []int // nil slice — len 0, cap 0, no allocation
b := []int{} // empty slice — len 0, allocated header
c := make([]int, 0) // empty slice — same as b
len,cap,range, andappendtreat all three identically.- Prefer the nil slice as the "no elements" value; don't allocate just to return "empty".
- Exception: JSON.
nilmarshals tonull, empty marshals to[]. If the API contract requires[], return an empty slice explicitly. - Never distinguish nil from empty in logic — check
len(s) == 0.
2. Append Semantics and Aliasing
append MAY return the same backing array or a new one. Both cases
bite:
// ❌ Bad — result may alias the input
func addSuffix(base []string) []string {
return append(base, "suffix") // if cap(base) > len(base),
} // this WRITES INTO base's array
// ✅ Good — force a copy when the input must not be touched
func addSuffix(base []string) []string {
out := make([]string, len(base), len(base)+1)
copy(out, base)
return append(out, "suffix")
}
// ❌ Bad — subslice keeps the whole 64 MB alive
func header(big []byte) []byte {
return big[:512] // backing array is still the full big
}
// ✅ Good — copy the window you keep
func header(big []byte) []byte {
return slices.Clone(big[:512]) // Go 1.21+; or copy() manually
}
Rule: a function either owns a slice or copies it. Returning a subslice of a caller's slice, or appending to one, silently shares memory.
3. Preallocation
When the final size is known or bounded, allocate once:
// ✅ Good — one allocation
names := make([]string, 0, len(users))
for _, u := range users {
names = append(names, u.Name)
}
// ❌ Bad — repeated growth and copying
var names []string
for _, u := range users {
names = append(names, u.Name)
}
Same for maps: make(map[string]int, len(items)).
Don't preallocate when the size is unknown — a wrong large cap wastes
memory; append growth is fine for cold paths.
4. Map Essentials
// Comma-ok distinguishes "missing" from "zero value"
count, ok := hits[key]
if !ok { /* key absent */ }
// Zero value reads are safe; writes to a nil map PANIC
var m map[string]int
_ = m["x"] // 0, fine
m["x"] = 1 // panic: assignment to entry in nil map — make() first
// Iteration order is RANDOM and differs between runs.
// Sort keys when output must be deterministic:
keys := slices.Sorted(maps.Keys(m)) // Go 1.23+
for _, k := range keys {
fmt.Println(k, m[k])
}
- Map values are not addressable:
m[k].Field = vdoesn't compile for struct values. Use a map of pointers, or read-modify-write. - Deleting during
rangeis safe; inserting duringrangeis unspecified (the new key may or may not be visited).
5. Sets
The idiomatic set is a map with empty-struct values:
seen := make(map[string]struct{}, len(items))
for _, it := range items {
if _, dup := seen[it.ID]; dup {
continue
}
seen[it.ID] = struct{}{}
process(it)
}
struct{} occupies zero bytes; map[string]bool also works and reads
better when you'll test membership with if seen[id].
6. Arrays vs Slices
- Arrays (
[4]byte) are values: assignment and passing copy the whole array. Comparable with==when elements are comparable. - Use arrays for fixed-size data with value semantics: hashes
(
[32]byte), IPv4 addresses, fixed matrices, map keys. - Everything else is a slice. A function taking
[100]intcopies 800 bytes per call — almost always wrong.
7. Choosing a Structure
| Need | Use |
|---|---|
| Ordered collection, growable | []T |
| Membership / dedup | map[K]struct{} |
| Key→value lookup | map[K]V |
| Fixed size, value semantics, comparable | [N]T array |
| FIFO queue (single goroutine) | slice with head index, or container/list for heavy churn |
| Stack | slice + append / s[:len(s)-1] |
| Concurrent map, write-once read-many keys | sync.Map — otherwise mutex + map |
sync.Map is a special-case tool (append-only caches, disjoint key
sets). Default to map + sync.RWMutex; see the concurrency skill for
locking patterns.
Verification Checklist
- No logic distinguishes nil slice from empty slice;
len()used for emptiness - JSON-facing slices explicitly empty (not nil) where the contract requires
[] - No
appendto a slice the function doesn't own; copies made explicit - No long-lived subslices of large arrays without
slices.Clone/copy - Slices and maps preallocated with capacity when size is known
- Comma-ok used wherever "missing" differs from zero value
- No writes to possibly-nil maps
- Deterministic output paths sort map keys before iteration
- Sets built as
map[K]struct{}(ormap[K]boolfor readability) - Arrays only where value semantics or comparability is the point
Repositorio GitHub
Preguntas frecuentes
¿Qué es el Skill go-data-structures?
go-data-structures es un Skill de Claude creado por eduardo-sl. Los Skills agrupan instrucciones y recursos que Claude carga cuando los necesita para realizar tareas relacionadas con go-data-structures sin indicaciones adicionales.
¿Cómo instalo go-data-structures?
Usa los comandos de instalación de esta página: añade go-data-structures a Claude Code como plugin o clona su repositorio en tu directorio de skills y reinicia Claude para cargarlo.
¿A qué categoría pertenece go-data-structures?
go-data-structures pertenece a la categoría Diseño.
¿Se puede usar go-data-structures gratis?
Sí. go-data-structures aparece en AIMCP y se puede instalar gratis.
Habilidades relacionadas
Utilice la habilidad executing-plans cuando tenga un plan de implementación completo para ejecutar en lotes controlados con puntos de revisión. Esta habilidad carga y revisa críticamente el plan, luego ejecuta tareas en pequeños lotes (por defecto 3 tareas) mientras reporta el progreso entre cada lote para la revisión del arquitecto. Esto asegura una implementación sistemática con puntos de control de calidad integrados.
Esta habilidad despacha un subagente revisor de código para analizar los cambios en el código frente a los requisitos antes de proceder. Debe usarse después de completar tareas, implementar funciones principales o antes de fusionar con la rama principal. La revisión ayuda a detectar problemas de forma temprana al comparar la implementación actual con el plan original.
Esta habilidad proporciona una guía integral para que los desarrolladores conecten servidores MCP a Claude Code mediante transportes HTTP, stdio o SSE. Cubre la instalación, configuración, autenticación y seguridad para integrar servicios externos como GitHub, Notion y APIs personalizadas. Úsala al configurar integraciones MCP, al configurar herramientas externas o al trabajar con el Protocolo de Contexto del Modelo de Claude.
Esta habilidad ayuda a los desarrolladores a elegir entre las interfaces web y CLI de Claude Code mediante el análisis de tareas, y luego permite la teletransportación fluida de sesiones entre estos entornos. Optimiza el flujo de trabajo gestionando el estado y el contexto de la sesión al cambiar entre web, CLI o móvil. Úsala para proyectos complejos que requieren diferentes herramientas en varias etapas.
