Beginner Fundamentals
Loops
Rust offers three loop keywords: loop, while, and for. Each suits a different repetition pattern.
loop
loop repeats forever until you break out of it.
fn main() {
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
}
println!("{}", count); // 3
}
break with a value
A loop can return a value through break.
fn main() {
let mut n = 1;
let result = loop {
n *= 2;
if n > 50 {
break n; // return n from the loop
}
};
println!("{}", result); // 64
}
while
while repeats as long as a condition is true.
fn main() {
let mut n = 3;
while n > 0 {
println!("{}", n);
n -= 1;
}
}
for
for iterates over a range or a collection.
fn main() {
for i in 1..=5 { // inclusive range 1 to 5
println!("{}", i);
}
let colors = ["red", "green", "blue"];
for color in colors {
println!("{}", color);
}
}
The for loop is the most common and the least error-prone.