break and continue
break leaves a loop at once. continue ends the current pass and moves on to the next one.
break-statement = "break" [label] ";"
continue-statement = "continue" [label] ";"
| Statement | In while and loop | In do while | In for |
|---|---|---|---|
break | leaves the loop | leaves the loop | leaves the loop |
continue | goes back to the condition (while) or the top (loop) | goes to the condition | moves to the next element |
for v in values {
if v == 0 {
break;
}
if v < 0 {
continue;
}
sum += v;
}
Without a label, both act on the innermost loop around them. Outside every loop they are errors: error: 'break' can only be used inside 'while', 'for', or 'loop', and the same for continue. break takes no value; a loop does not produce one.
Labels
A label names a loop. It is written before the loop keyword, followed by :, and any of the four loops may carry one:
outer: for row in 0..3 {
for col in 0..3 {
if col == 2 {
continue outer;
}
if row == 2 {
break outer;
}
Print("({} {}) ", row, col);
}
}
continue outer abandons the inner loop and starts the next pass of outer; break outer leaves both. This prints (0 0) (0 1) (1 0) (1 1).
A label names exactly one loop at a time. An inner loop may not reuse the label of a loop around it, because break outer inside it would then read as either one:
error: loop label 'outer' shadows an enclosing loop label
help: give the inner loop a different label
Loops that follow one another, rather than nest, may reuse a label. A label must belong to a loop that encloses the statement: continue missing; is error: 'continue' refers to unknown loop label 'missing'. Only loops take labels.
Inside expressions
break and continue, with or without a label, may also stand where an expression would leave rather than produce a value: as a whole match arm, or as the fallback of ??:
for v in values {
let step = match v {
0 => break,
-1 => continue,
else => v
};
sum += step;
}
for v in values {
let x = maybe ?? continue;
PrintLine("{}", x);
}
They cannot be used as an ordinary value: n > 0 ? n : break is error: 'break' cannot be used as a value here.