for
loop GO-S1011for
statement has three major parts, i.e., "init", "condition" and "post iteration" statements. The "init", "condition" and "post iteration" should be correctly used to get the intentional behavior. Inconsistent statements might lead to runtime panics, etc., and not likely to be intentional but typos instead. The code should be carefully vetted as it might be intentional in some rare cases where the condition is being handled inside the for
body.
In the following example, the fillZero
function zeroes a slice from index n
to len(a)-1
. But the post iteration statement, i.e., i--
seems to be inconsistent with the expected behavior of the for
statement, and it should be instead i++
to get the expected behavior.
func fillZero(a []int, n int) {
// zero out `a` above index `n` but as a result
// of typo, i is decremented instead of being incremented.
// Here, the `for`'s post iteration statement is erroneous.
// If not fixed, there could be runtime panic because `i` would
// try to access elements out of bounds.
for i := index; i < len(a); i-- {
a[i] = 0
}
}
func fillZero(a []int, n int) {
// zero out `a` above index `n`
for i := index; i < len(a); i++ {
a[i] = 0
}
}