Rust Loops
ExampleRust
fn main() {
for i in 1..=3 {
println!("for {}", i);
}
let mut n = 3;
while n > 0 {
println!("while {}", n);
n -= 1;
}
let mut count = 0;
let found = loop {
count += 1;
if count == 4 {
break count * 10;
}
};
println!("{}", found);
for (i, c) in "Rs".chars().enumerate() {
println!("{} {}", i, c);
}
}Output
for 1 for 2 for 3 while 3 while 2 while 1 40 0 R 1 s
1..=3 is a range including 3. loop repeats forever until you break, and break can even hand back a value.
Quick check
Which range includes both ends?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.