The loop Keyword
loop makes your program repeat something forever, until you tell it to stop.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
fn main() {
let mut count = 0;
loop {
count += 1;
println!("count = {}", count);
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
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 2;
}
};
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
fn main() {
let mut total = 0;
'outer: loop {
let mut inner_count = 0;
loop {
total += 1;
inner_count += 1;
if inner_count == 2 {
break;
}
if total >= 6 {
break 'outer;
}
}
if total >= 6 {
break;
}
}
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
fn main() {
let mut attempts = 0;
let success = loop {
attempts += 1;
if attempts == 3 {
break true;
}
};
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: