This rule raises an issue when a reserved identifier is shadowed by a definition or declaration.
Go declares a set of identifiers in the universe block, the outermost scope of a program:
any, bool, byte, comparable, complex64, complex128,
error, float32, float64, int, int8, int16, int32,
int64, rune, string, uint, uint8, uint16, uint32,
uint64, and uintptrtrue, false, and iotanilappend, cap, clear, close, complex, copy,
delete, imag, len, make, max, min, new,
panic, print, println, real, and recoverThese are ordinary identifiers and not keywords, so any inner scope is free to declare its own identifier with one of those names. Such a declaration is valid Go, and it shadows the predeclared identifier for the rest of the enclosing scope. Nothing in the code that follows signals that the name no longer means what it usually means:
fmt.Println("true value:", true) // prints "true value: true"
true := false // Noncompliant: "true" now names a local variable
fmt.Println("true value:", true) // prints "true value: false"
Any declaration that binds a name can shadow a predeclared identifier, including short variable declarations, var and
const declarations, function and type declarations, function parameters, named results, and range clauses.
A reader has to notice the shadowing declaration to understand the code that follows it, and a reviewer reading a diff usually sees only a part of the scope. Code that behaves one way where it was written behaves differently once it is moved, copied, or extracted into a scope where the name is not shadowed, and the compiler reports nothing.
The predeclared identifier also becomes unreachable for the rest of the scope. After len := len(values), a later call to
len(other) does not compile, and after string := "values", a later var s string does not compile either. This
forces either a workaround or a rename in the middle of unrelated work.
Rename the declaration to a name that does not collide with a predeclared identifier. The value being named usually suggests a good replacement: a
variable holding len(values) is a count or a size, and a boolean is an isEmpty or a
found.
func describe(values []int) string {
len := len(values) // Noncompliant: "len" is a predeclared function
true := len == 0 // Noncompliant: "true" is a predeclared constant
string := "values" // Noncompliant: "string" is a predeclared type
if true {
return "no " + string
}
return fmt.Sprintf("%d %s", len, string)
}
func describe(values []int) string {
count := len(values)
isEmpty := count == 0
label := "values"
if isEmpty {
return "no " + label
}
return fmt.Sprintf("%d %s", count, label)
}