while loop
while loop
Function
while will evaluate the condition before each loop starts. The loop body is executed when the condition is true and ends when the condition is false. It is suitable for scenarios where "you are not sure how many times you want to loop, but you know the continuation condition".
Syntax
while condition { statement } while:label condition { break:label }
Example
i = 0 while i < 3 { println i i += 1 }
Break and Skip
break ends the current cycle, continue enters the next round of condition judgment. Labels can be used in nested loops, such as while:outer with break:outer.
Notes
- The loop body must give the condition a chance to become false, otherwise an infinite loop will form.
- The
whilestatement itself returnsempty.