In Rust, loop is the most fundamental looping construct. Unlike for or while, which depend on conditions or iterators, a loop will run indefinitely unless you explicitly tell it to stop.
Loop is powerful tool when you need a cycle that only ends when your program decides so.
The Basic loop Statement #
The simplest usage of loop is an infinite loop:
fn main() {
loop {
println!("This will print forever!");
}
}Code language: Rust (rust)Running this will keep printing endlessly until you manually stop the program (Ctrl + C in terminal).
Breaking Out of a Loop #
To stop a loop, you use the break keyword:
fn main() {
let mut counter = 0;
loop {
println!("Counter: {}", counter);
counter += 1;
if counter == 5 {
break; // exits the loop
}
}
println!("Loop finished!");
}
Code language: Rust (rust)Output:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Loop finished!
Code language: Rust (rust)Returning Values from a Loop #
One special feature of Rust is that loops can return values when you use break with a value:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // returns 20
}
};
println!("Result: {}", result);
}
Code language: Rust (rust)Output:
Result: 20Code language: Rust (rust) This makes loop more powerful than a plain infinite loop.
Using continue to Skip Iterations #
Just like in other languages, continue skips the current iteration and jumps to the next one:
fn main() {
let mut number = 0;
loop {
number += 1;
if number % 2 == 0 {
continue; // skip even numbers
}
println!("Odd number: {}", number);
if number >= 7 {
break;
}
}
}
Code language: Rust (rust)Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Code language: Rust (rust)Labeled Loops (Nested Loops Control) #
In Rust, loops can have labels. This is helpful when you have nested loops and want to break or continue a specific one.
fn main() {
let mut outer = 0;
'outer_loop: loop {
let mut inner = 0;
loop {
println!("outer = {}, inner = {}", outer, inner);
inner += 1;
if inner == 3 {
break; // breaks only inner loop
}
if outer == 2 && inner == 2 {
break 'outer_loop; // breaks the outer loop
}
}
outer += 1;
}
println!("All done!");
}
Code language: Rust (rust)Output:
outer = 0, inner = 0
outer = 0, inner = 1
outer = 1, inner = 0
outer = 1, inner = 1
outer = 2, inner = 0
outer = 2, inner = 1
All done!
Code language: Rust (rust)When to Use loop #
Use loop when:
- You need a truly infinite loop until an internal condition stops it.
- You want to return a value from inside a loop.
- You’re working with nested loops and need labeled control.
For other cases, while or for is usually more straightforward.
Summary #
loop {}creates an infinite loop.- Use
breakto exit, optionally with a return value. - Use
continueto skip the current iteration. - Loops can be labeled to control nested structures.
loopis the most flexible looping construct in Rust.