107 / Fundamentals

continue in for

continue inside a for ... in skips to the next element, the same way it already did inside a while. This recipe shows it in both forms of for: iterating an Array and iterating a range.

107-for-continue.nxSource →
// `continue` dentro de un `for ... in` — sobre un array y sobre un rango —
// salta al siguiente elemento, igual que en `while`.

fn main() -> int {
    // for sobre un ARRAY
    let numeros: Array = [1, 2, 3, 4, 5, 6]
    for n: int in numeros {
        if n % 2 == 0 {
            continue
        }
        print("impar: " + int_to_string(n))
    }

    // for sobre un RANGO
    for i in 0..6 {
        if i == 3 {
            continue
        }
        print("i = " + int_to_string(i))
    }

    return 0
}
Outputstdout
impar: 1
impar: 3
impar: 5
i = 0
i = 1
i = 2
i = 4
i = 5

How it works

The first loop walks numeros with for n: int in numeros. When n is even, continue cuts that pass short without running the print that follows, so only the odd numbers get printed.

The second loop does the same over a range, for i in 0..6: when i is 3, continue skips just that iteration and moves on to 4 — the range itself is not cut short, only that one value is skipped.