go-modernize
Acerca de
Esta habilidad moderniza código Go actualizándolo para utilizar las características más recientes del lenguaje desde Go 1.21-1.23+, incluyendo genéricos, log/slog, errors.Join y los paquetes slices/maps. Úsala específicamente cuando quieras refactorizar patrones heredados como `interface{}` o adoptar características como range-over-func e iteradores. No está destinada para estilo general, filosofía de errores o arquitectura de logging — utiliza otras habilidades especializadas para esos aspectos.
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-modernizeCopia y pega este comando en Claude Code para instalar esta habilidad
Documentación
Go Modernize
Go evolves. Code written for Go 1.16 should not look the same as code targeting
Go 1.22+. Modernize incrementally — update go.mod, then adopt new patterns.
Detailed reference material, loaded on demand:
references/generics.md— replacinginterface{}with type parameters, constraints, generic containers, when NOT to use generics.references/stdlib-migrations.md— before/after examples for slog, errors.Join, slices/maps helpers, range-over-int, and iterators.
Read a reference file only when the summary below is not enough.
Modernization Procedure
-
Check the
godirective ingo.mod— it caps which features you can use. -
Run the official modernize analyzer first — it finds and fixes the mechanical migrations automatically:
go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...If the command is unavailable in your environment, apply the table below manually instead.
-
Scan the table below for the judgment-based migrations the analyzer does not cover (generics, iterators, logger replacement) and apply them case by case.
-
Run
go build ./...and the test suite after each group of changes.
Feature Table by Go Version
| Go Version | Feature | Action |
|---|---|---|
| 1.13+ | errors.Is, errors.As | Replace == error comparisons |
| 1.13+ | http.NewRequestWithContext | Replace http.NewRequest |
| 1.16+ | embed | Replace go-bindata / packr |
| 1.18+ | Generics | Replace interface{} utility functions |
| 1.20+ | errors.Join | Replace manual error accumulation |
| 1.21+ | log/slog | Replace log for structured logging |
| 1.21+ | slices, maps | Replace hand-written slice/map utilities |
| 1.21+ | min, max builtins | Replace math.Min/math.Max (float64-only) |
| 1.22+ | Range over int | Replace for i := 0; i < n; i++ |
| 1.23+ | Range over func | Replace callback-based iteration |
Key Migrations at a Glance
Generics — type-safe utilities (Go 1.18+)
// ❌ Before — loses type safety
func Contains(slice []interface{}, target interface{}) bool { /* ... */ }
// ✅ After — type-safe generic
func Contains[T comparable](slice []T, target T) bool { /* ... */ }
Use generics for container types (Set[T], Result[T]) and utility
functions. Do NOT use them where a single concrete type works, or as a
substitute for interfaces in runtime polymorphism.
Details and constraint patterns: references/generics.md.
Structured logging (Go 1.21+)
// ❌ Before
log.Printf("processing order %s for user %s", orderID, userID)
// ✅ After
slog.Info("processing order",
slog.String("order_id", orderID),
slog.String("user_id", userID),
)
Keep zap/zerolog only if you need their performance for high-throughput logging; for most services slog is sufficient.
errors.Join (Go 1.20+)
var errs []error
for _, item := range items {
if err := validate(item); err != nil {
errs = append(errs, err)
}
}
if err := errors.Join(errs...); err != nil {
return fmt.Errorf("validation: %w", err)
}
errors.Join preserves the chain — errors.Is/errors.As work on each
joined error. Never accumulate error strings manually.
slices and maps helpers (Go 1.21+)
found := slices.Contains(items, target) // not a manual loop
slices.SortFunc(users, func(a, b User) int { // not sort.Slice
return cmp.Compare(a.Name, b.Name)
})
keys := slices.Collect(maps.Keys(m)) // not a manual key loop
clone := maps.Clone(m) // not a manual copy loop
Range over int (Go 1.22+) and iterators (Go 1.23+)
for i := range n { process(i) } // not for i := 0; i < n; i++
for i, v := range slices.Backward(items) { // stdlib iterators
fmt.Printf("%d: %v\n", i, v)
}
Custom iter.Seq/iter.Seq2 iterators replace callback-based iteration —
full worked example in references/stdlib-migrations.md.
Context-aware HTTP requests (Go 1.13+, often missed)
// ❌ Before — request without context
req, err := http.NewRequest(http.MethodGet, url, nil)
// ✅ After — context propagated
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
Verification Checklist
go.modversion matches the features used in the codebase- No
interface{}whereanyor type parameters would be clearer log/slogused instead oflog.Printffor structured loggingerrors.Joinused instead of manual error string concatenationslices.Contains,slices.SortFunc,maps.Clonereplace hand-written loops- Range over int (
for i := range n) used where applicable http.NewRequestWithContextused instead ofhttp.NewRequest- No
sort.Slice— useslices.SortFuncwithcmp.Compare - Generics used for type-safe containers and utilities, not overused for trivial cases
- Third-party dependencies evaluated against stdlib alternatives added in recent Go versions
Repositorio GitHub
Preguntas frecuentes
¿Qué es el Skill go-modernize?
go-modernize 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-modernize sin indicaciones adicionales.
¿Cómo instalo go-modernize?
Usa los comandos de instalación de esta página: añade go-modernize 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-modernize?
go-modernize pertenece a la categoría Desarrollo.
¿Se puede usar go-modernize gratis?
Sí. go-modernize aparece en AIMCP y se puede instalar gratis.
Habilidades relacionadas
qmd es una herramienta CLI de búsqueda e indexación local que permite a los desarrolladores indexar y buscar en archivos locales mediante búsqueda híbrida que combina BM25, embeddings vectoriales y reranking. Es compatible tanto con uso desde la línea de comandos como con modo MCP (Model Context Protocol) para integración con Claude. La herramienta utiliza Ollama para los embeddings y almacena los índices localmente, lo que la hace ideal para buscar documentación o bases de código directamente desde la terminal.
Esta habilidad ejecuta planes de implementación asignando un nuevo subagente para cada tarea independiente, con revisión de código entre tareas. Permite una iteración rápida mientras mantiene controles de calidad a través de este proceso de revisión. Úsala cuando trabajes en tareas mayormente independientes dentro de la misma sesión para garantizar un progreso continuo con verificaciones de calidad integradas.
La habilidad mcporter permite a los desarrolladores gestionar y llamar servidores del Protocolo de Contexto de Modelo (MCP) directamente desde Claude. Proporciona comandos para listar servidores disponibles, llamar a sus herramientas con argumentos, y manejar la autenticación y el ciclo de vida del daemon. Utiliza esta habilidad para integrar y probar la funcionalidad de servidores MCP en tu flujo de trabajo de desarrollo.
Esta habilidad despliega y orquesta agentes Vertex AI ADK utilizando el protocolo A2A, gestionando el descubrimiento de AgentCard, el envío de tareas y soportando herramientas como el Sandbox de Ejecución de Código y el Banco de Memoria. Permite construir sistemas multiagente con patrones de orquestación secuencial, paralela o en bucle en Python, Java o Go. Úsela cuando se le solicite desplegar agentes ADK u orquestar flujos de trabajo de agentes en Google Cloud.
