go-modernize
Guidelines for updating legacy Golang code to use modern features (Go 1.21+). Covers generics, slog, slices/maps packages, and more.
SKILL.mdskills/go/go-modernize/SKILL.md
GitHubModern Go Checklist (1.21 - 1.24)
- Use
anyinstead ofinterface{}(Go 1.18+). - Use
minandmaxbuilt-in functions (Go 1.21+). - Use
clearto empty maps and slices (Go 1.21+). - Use
slicesandmapspackages for common operations (Sort, Contains, Clone, Keys) (Go 1.21+). - Migrate to
log/slogfor structured logging (Go 1.21+). - Use
rangeover integers (e.g.,for i := range 10) (Go 1.22+). - Use
cmp.Orfor concise default value assignment (Go 1.22+). - Use
math/rand/v2for better performance and API (Go 1.22+). - Use Iterators (
iterpackage) for custom collection traversal (Go 1.23+). - Use
b.Loop()for benchmarks (Go 1.24+). - Use
t.Context()for test-scoped cancellation (Go 1.24+).
Modernization Examples
1. Slices and Maps (1.21+)
// ✅ Modern
import "slices"
if slices.Contains(mySlice, "value") { ... }
// ❌ Old
for _, v := range mySlice {
if v == "value" { ... }
}
2. Min/Max (1.21+)
// ✅ Modern
val := min(a, b, c)
// ❌ Old
val := a
if b < val { val = b }
if c < val { val = c }
3. Range over Int (1.22+)
// ✅ Modern
for i := range 10 {
fmt.Println(i)
}
// ❌ Old
for i := 0; i < 10; i++ {
fmt.Println(i)
}
4. Structured Logging (1.21+)
// ✅ Modern (stdlib)
slog.Info("user logged in", "user_id", id)
// ❌ Old (third-party or non-structured)
log.Printf("user %d logged in", id)
Deprecated Package Replacements
| Deprecated | Modern Replacement |
|---|---|
math/rand |
math/rand/v2 |
io/ioutil |
os or io |
reflect.PtrTo |
reflect.PointerTo |
runtime.SetFinalizer |
runtime.AddCleanup (Go 1.24) |
Strategy for Modernization
- Check
go.modversion: Ensure the project targets a recent Go version. - Safety First: Fix patterns that lead to bugs (e.g., loop variable shadowing in pre-1.22).
- Readability: Replace manual loops with
slices/mapsfunctions. - Tooling: Use
golangci-lintwith themodernizelinter enabled. - Incremental: Don't refactor the whole codebase at once; modernize as you touch files for other features.
Anti-patterns
- ❌ Mixing old and new styles — e.g., using
interface{}in some places andanyin others. - ❌ Ignoring
log/slog— Sticking tolog.Printfin new production services. - ❌ Manual
min/maximplementations — Using custom helper functions instead of the built-ins. - ❌ Ignoring
go mod tidy— Not keeping the toolchain version updated ingo.mod.