Sometimes a function, variable, constant, field, or whole package becomes redundant or unnecessary but must be kept for compatibility with existing programs. These should not be used except for compatibility with legacy systems.
true
is implicit in switch
statements CRT-A0015If no tag is given with switch
, it assumes true
.
if
statement for single bool judgment GO-R1004if
statement can be simplified where only a single bool judgment is happening. It is more
idiomatic not to store the result of a function returning a bool and compare that in if
statement's conditional. It is better to skip the initialization expression.
any
instead of interface{}
GO-R3001In Go 1.18+, empty interface (interface {}
) is recommended to be replaced by
any
.
time.Sleep
instead of single case select
SCC-S1037Instead of using a single case in a select
statement that receives results from
time.After
is preferable to simply use time.Sleep
.
Self-assignment of variables is pointless and should be avoided.
Every constant in a constant declaration block needs to have a type unless
the iota
construct is used
fallthrough
in switch statement can be avoided CRT-A0003Empty fallthrough
can be avoided by clubbing together consecutive cases, using
multi-case values.
It is not recommended to use len
for empty string test.
It is not recommended to use method expression instead of method call.
string
and []byte
CRT-A0007Conversion between string
and []byte
is not required here, and it is better
to pass the string
as copy's argument as it is without type conversing it to
[]byte
.
It is not recommended to use unnecessary blocks.
It is legal and idiomatic to swap values of two variables using "tuple assignment" instead of swapping them in multiple statements.
Certain functions, for a particular set of arguments, have shorthands (helpers) that can be used instead.
if
can be replaced with else if
CRT-A0011A single nested if
inside an else
block can be replaced with an else if
.
switch
with single case can be rewritten as if
or if-else
CRT-A0014switch
statements with a single case
can be rewritten as if-else
or if
.
If a value is of type slice already, it need not be converted to slice again.
Function literals that only call a single function, without making any other changes to the value of the inner function, can be removed, as they are redundant. Instead, the inner function, that is being called inside the outer function should be called.
io/ioutil
package usage GO-C4001io/ioutil
package, like most things with util in the name, has turned out to
be a poorly defined and complex to understand the collection of things.
new
expressions GO-C4002It is recommended to replace the immediate dereferencing of new
expressions to
the equivalent zero value of the type, i.e., new
returns a pointer to a newly
allocated zero value of the type passed as an argument to new
, so
dereferencing the same gives the zero value.