In Rust, the for loop is used when you want to repeat a block of code a certain number of times or when you want to go through a sequence of items.
Basic for Loop Syntax #
The general syntax looks like this:
for variable in sequence {
// code block
}
Code language: Rust (rust)variableis a name you choose that will represent each step.sequencetells Rust how many times to repeat the loop (later, this can be an array, a range, or other iterators).- The
{ ... }block contains the code that runs each time.
Repeating an Action a Fixed Number of Times Example #
For now, let’s just simulate repeating something 3 times:
fn main() {
for _ in 0..3 {
println!("Hello, Rust!");
}
}Code language: Rust (rust)Output:
Hello, Rust!
Hello, Rust!
Hello, Rust!Explanation:
0..3is a range from 0 up to (but not including) 3.- The
_means we don’t care about the actual number; we just want the repetition. - This prints “Hello, Rust!” three times.
Using the Loop Variable #
If you want to know which step you are on, give the loop variable a name:
fn main() {
for i in 0..5 {
println!("Step number: {}", i);
}
}Code language: Rust (rust)This will print:
Step number: 0
Step number: 1
Step number: 2
Step number: 3
Step number: 4
Code language: Rust (rust)break in a for Loop #
You can stop the loop early with break:
fn main() {
for i in 0..10 {
if i == 5 {
println!("Stopping at {}", i);
break;
}
println!("Number: {}", i);
}
}Code language: Rust (rust)Output will stop at 5.
continue in a for Loop #
You can skip a particular step with continue:
fn main() {
for i in 0..6 {
if i % 2 == 0 {
continue; // skip even numbers
}
println!("Odd number: {}", i);
}
}Code language: Rust (rust)Only odd numbers (1, 3, 5) are printed.
Summary #
- The
forloop repeats code for each item in a sequence. 0..nis often used to repeat codentimes.- Use
breakto exit early,continueto skip one step.
Was this Helpful ?