Tsallaka zuwa abun ciki
Justice Tech School

Rust Loops

loop repeats forever until break and can return a value. while checks a condition and for iterates ranges and collections. Labels like 'outer break nested loops.

Example
let mut n = 0;
let r = loop { n += 1; if n == 5 { break n * 2; } };
println!("{}", r);
for i in (1..=3).rev() { print!("{} ", i); }
println!();
let mut c = 3;
while c > 0 { c -= 1; }
println!("{}", c);

Result

10
3 2 1 
0

Exercise

Infinite loop.

 { break; }

Quiz Test

What can loop return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.