Repeat until a condition changes
Use while when a condition determines how long to repeat. The condition must
be bool, and it is checked before every iteration, including the first:
def main() -> Result[(), IoError | OverflowError[i64]]:
mut remaining = 3
while remaining > 0:
print(remaining)?
remaining = remaining - 1
print("go")?
Ok(())
3
2
1
go
continue skips the rest of the current iteration. break exits the loop:
def main() -> Result[(), IoError | OverflowError[i64] | ZeroDivisionError]:
mut n = 0
while True:
n = n + 1
if n % 2 == 0:
continue
if n > 5:
break
print(n)?
Ok(())
1
3
5
Update the condition’s inputs before a continue when needed; otherwise a
while loop can repeat forever. In a for loop, continue automatically
advances to the next element:
def main() -> Result[(), IoError]:
for n in range(6):
if n == 1:
continue
if n == 4:
break
print(n)?
Ok(())
0
2
3
break and continue affect only the innermost loop. Use return to leave
the function. break cannot carry a value, and loop else clauses are not
supported.
Even after while True, a function returning data still needs a result after
the loop.
Statements directly after an unconditional exit are rejected:
def main() -> Result[(), IoError]:
while True:
break
print("unreachable")?
Ok(())
unreachable statement after a control-flow exit