Repeating with While
Sometimes you want your program to do the same thing over and over again. That's where while loops come in! A while loop keeps running a block of code as long as a condition is true.
Your First While Loop
Let's break this down:
let mut count = 1;— We create a mutable variable (that's whatmutmeans — it can change!)while count <= 5— Keep looping as long ascountis 5 or lesscount += 1;— Add 1 tocounteach time through the loop- No parentheses around the condition — Rust doesn't need them!
- Curly braces
{}are always required around the loop body
Counting Backwards
You can count down too! Just start high and subtract:
The loop Keyword
Rust has a special keyword called loop that creates an infinite loop — it runs forever unless you tell it to stop with break:
The break statement immediately exits the loop. Without it, this loop would run forever!
Skipping with continue
Sometimes you want to skip the rest of the loop body and jump to the next round. That's what continue does:
This prints only the odd numbers from 1 to 9. When i is even, continue skips the println! and goes back to the top of the loop.
Watch Out for Infinite Loops!
If the condition never becomes false, your loop will run forever. Always make sure something inside the loop changes the condition:
Forgetting x += 1; would make this loop print 1 forever. Always double-check that your loop will eventually stop!
Summary
| Concept | What it does |
|---|---|
while condition { } | Repeats while condition is true |
loop { } | Repeats forever (until break) |
break | Exits the loop immediately |
continue | Skips to the next iteration |
let mut | Creates a variable that can change |
Now let's practice writing some loops!