Every branch of an if-else is the same

tx0/go:identical-branchesdefaultwarningbug

What it finds

if c { f() } else { f() }: when every branch of an if does the same, the condition decides nothing. Usually one branch was copied and not changed.

A plain if with an else is checked, and so is an else if chain that ends in a plain else, but only as a whole: in a chain, giving each case its own branch even where two do the same is a common way to list the cases, as code generators do. When every branch of the chain is the same, though, none of its conditions matters. A chain with an init statement after its first if is left alone, since the same text can then refer to different variables in different branches.

Empty blocks are left alone, and so are switches whose cases all do the same: a switch with one case and a default that do the same is a common placeholder for cases still to come.

From the rule's source, identical_branches.rs.

Example from the rule's tests
package p func f(ok bool, n int) int {	if ok {tx0 reports: both branches of this if do the same		n = 1	} else {		n = 1	}	if n > 0 && ok {tx0 reports: both branches		return g(n)	} else {		// The same, but with a comment.		return g(n)	}	if ok {		n = 1	} else {		n = 2	}	if ok {	} else {	}	if ok {		n = 1	} else if n > 2 {		n = 2	} else {		n = 2	}	if ok {		n = 1	} else if n > 2 {		n = 1	}	if ok {tx0 reports: every branch of this if chain does the same		n = 1	} else if n > 2 {		n = 1	} else {		n = 1	}	if v := g(n); v > 0 {tx0 reports: every branch		n = v	} else if v > 1 {		n = v	} else {		n = v	}	if v := g(n); v > 0 {		n = v	} else if v := g(2); v > 1 {		n = v	} else {		n = v	}	return n} func g(n int) int { return n }
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:identical-branches" = "off"

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:identical-branches] reason="..."

tx0 explain tx0/go:identical-branches shows the same in the terminal. Found a false positive? Report it.