What is modernize?
modernize suggests behavior-preserving refactors that use newer Go features and standard library helpers.
It may be integrated into IDE (e.g. via gopls in vscode or neovim). It may also be run directly from the CLI over a whole codebase by:
go run golang.org/x/tools/go/analysis/passes/modernize/cmd/modernize@latest -fix ./...
Example 1: prefer strings.CutPrefix over manual prefix slicing
replace:
if strings.HasPrefix(s, "maciej") {
s = s[len("maciej"):]
}with:
if after, ok := strings.CutPrefix(s, "maciej"); ok {
s = after
}Example 2: membership checks with slices.Contains()
replace:
found := false
for _, v := range xs {
if v == needle {
found = true
break
}
}with:
found := slices.Contains(xs, needle)
Example 03: map clone with maps.Clone
replace:
dst := make(map[string]int, len(src))
for k, v := range src {
dst[k] = v
}with:
dst := maps.Clone(src)
Example 04: Prefer any over interface{}
replace:
var x interface{}
with:
var x any
Example 05: prefer range over integers
replace:
for i := 0; i < 5; i++ {}
with:
for i := range 5 {}
How to enable it
With golangci-lint - set inside .golangci.yaml:
linters:
enable:
- modernizeor:
golangci-lint run --enable modernize