The loop Keyword
loop makes your program repeat something forever, until you tell it to stop.loop {
// body
if condition {
break;
}
}
A Basic Infinite Loop
The loop keyword repeats its block forever until a break statement explicitly exits it. This is useful when you don't know ahead of time how many iterations you need.
Example: A Basic Infinite Loop
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `count`, initialized to `0`
let mut count = 0;
// Loop forever until an explicit `break`
loop {
count += 1;
// Print "count = {}" to the console, substituting in `count` (with a trailing newline)
println!("count = {}", count);
// Check whether `count == 3`
if count == 3 {
break;
}
}
}
Login to try C/C++/Java/PHP code in the editor
Returning a Value from loop
Unlike most looping constructs, loop is an expression: you can pass a value to break, and that becomes the value the whole loop expression evaluates to.
Example: Returning a Value from loop
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `counter`, initialized to `0`
let mut counter = 0;
// Declare an immutable variable `result`; its value comes from the block below
let result = loop {
counter += 1;
// Check whether `counter == 5`
if counter == 5 {
break counter * 2;
}
};
// Print "result = {}" to the console, substituting in `result` (with a trailing newline)
println!("result = {}", result);
}
Login to try C/C++/Java/PHP code in the editor
Labeled Loops
When loops are nested, you can label the outer one with a name like 'outer: and use that label with break or continue to control the outer loop directly from inside the inner one.
Example: Labeled Loops
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `total`, initialized to `0`
let mut total = 0;
'outer: loop {
// Declare a mutable variable `inner_count`, initialized to `0`
let mut inner_count = 0;
// Loop forever until an explicit `break`
loop {
total += 1;
inner_count += 1;
// Check whether `inner_count == 2`
if inner_count == 2 {
break;
}
// Check whether `total >= 6`
if total >= 6 {
break 'outer;
}
}
// Check whether `total >= 6`
if total >= 6 {
break;
}
}
// Print "total = {}" to the console, substituting in `total` (with a trailing newline)
println!("total = {}", total);
}
Login to try C/C++/Java/PHP code in the editor
loop for Retry Logic
A common real-world use of loop is retrying an operation until it succeeds, checking a condition somewhere inside the body rather than only at the top.
Example: loop for Retry Logic
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `attempts`, initialized to `0`
let mut attempts = 0;
// Declare an immutable variable `success`; its value comes from the block below
let success = loop {
attempts += 1;
// Check whether `attempts == 3`
if attempts == 3 {
break true;
}
};
// Print "Succeeded after {} attempts: {}" to the console, substituting in `attempts, success` (with a trailing newline)
println!("Succeeded after {} attempts: {}", attempts, success);
}
Login to try C/C++/Java/PHP code in the editor
- Writing an infinite
loopand forgetting abreakcondition, causing the program to hang forever. - Not realizing
loopcan return a value viabreak value;, and manually tracking a result variable instead. - Confusing
loop(always repeats) withwhile(repeats only while a condition holds).
looprepeats a block of code indefinitely until abreakstatement is reached.break value;can exit aloopwhile also producing a value theloopexpression evaluates to.- Loop labels (
'outer: loop { ... }) letbreak/continuetarget a specific outer loop. loopis often used for retry logic or when the exit condition is checked in the middle of the body.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: