The init statement of an if names a value that only its condition reads
What it finds
if n := len(items); n > 10 { where n is used nowhere else: the variable only renames the expression for one comparison, so the reader has to follow the name to learn what is tested. if len(items) > 10 { says it directly.
Reported is the variable of an if statement's short declaration of one variable from one expression, when the variable is read exactly once, in the condition, and nowhere in the branches. Error variables, for which if err := f(); err != nil is the common form, are left alone.
From the rule's source, if_init_only_in_condition.rs.
package p func f(items []int, m map[string]int) int { if n := len(items); n > 10 {tx0 reports: n is used only in the condition return 1 } if v, ok := m["a"]; ok { return v } if n := len(items); n > 3 { return n } if err := check(); err != nil { return 0 } return 2} func check() error { return nil } Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:if-init-only-in-condition" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:if-init-only-in-condition] reason="..."tx0 explain tx0/go:if-init-only-in-condition shows the same in the terminal. Found a false positive? Report it.