for Loop ExamplesUse for to loop through a range of numbers. Use an inclusive top range with i32 MAX.
This page was last reviewed on Feb 10, 2023.
For loop. Consider a range of numbers—0, 1, 2. A for-loop can step through this range, with minimal syntax and clear code in Rust.
An important consideration. Is the for-loop supposed to include, or exclude the second number in the range? We can do both with special Rust syntax.
Inclusive for. This program uses the most common, and probably clearest, syntax for iteration in Rust. It starts at a number, and ends when a second number is reached.
Important The range looped over by for is exclusive, so the second number is never reached in the loop body.
fn main() { // Loop over first 3 numbers. // ... The top bounds is exclusive (not included). for i in 0..3 { println!("Hello: {}", i) } }
Hello: 0 Hello: 1 Hello: 2
Inclusive for. Sometimes, like when looping up the maximum integer value in a type, we want to include the second number. We can use the equals sign in the range for this.
Here We loop over the last 4 numbers in the i32 type. We use the i32 MAX constant to avoid having to type out the entire number.
fn main() { // Loop over last 4 numbers in the i32 type. // ... Use "=" in range to include that number. // Use "i32::MAX." for i in i32::MAX - 3..=i32::MAX { println!("I: {}", i) } }
I: 2147483644 I: 2147483645 I: 2147483646 I: 2147483647
For each loop. We can use a for-in loop over a vector or slice. Here we create a vector and push 3 integers to it. Then we use it in 2 for-loops, one after the other.
String Array
Important We must borrow the vector in the first for-loop so that it is not moved into the loop.
Info If we do not borrow the vector in the first for-loop, it would become unavailable for later use.
to owned
Detail If we want to use a for-in loop but do not care about the elements, we can use an underscore "_" to eliminate compiler warnings.
fn main() { let mut values = vec![]; values.push(10); values.push(20); values.push(30); // Use for-loop over values. // Borrow the vector so we can use it in the next loop. for value in &values { println!("VALUE: {}", value); } // We can ignore the iteration variable if we want. for _ in &values { println!("ITERATION"); } }
Loop keyword. For complex loops with unknown end points, an infinite loop with a condition that tests for the end point is often best. In Rust we can use the "loop" keyword for this.
Tip The loop keyword is like a "while true" loop. It is important to always test for the end condition in the loop body.
Also We should make sure to have a "mut" local variable for the index variable, and increment or decrement it on each iteration.
fn main() { let mut test = 10; loop { // Test for modulo 5. if test % 5 == 0 { println!("Divisible by 5: {}", test); } // End at zero. if test == 0 { break; } println!("Loop current: {}", test); test -= 1 } }
Divisible by 5: 10 Loop current: 10 Loop current: 9 Loop current: 8 Loop current: 7 Loop current: 6 Divisible by 5: 5 Loop current: 5 Loop current: 4 Loop current: 3 Loop current: 2 Loop current: 1 Divisible by 5: 0
Enumerate. Consider the for-in loop: we may often want to get both the element value at each index, and the index itself. We can use enumerate() to get these 2-value pairs.
Tip We call enumerate() on the result of iter(). We can get the 2 values from the tuple directly in the for-loop.
Here We access the 3 elements from the str array, alongside the 3 indexes (0, 1 and 2).
fn main() { let items = ["chair", "computer", "screen"]; // Use enumerate to get an index and value for each element. for (i, item) in items.iter().enumerate() { println!("ITEM: {} = {}", i, item); } }
ITEM: 0 = chair ITEM: 1 = computer ITEM: 2 = screen
While loop. Rust supports the while-keyword, and this is the classic while loop. It continues iterating while the specified condition is true.
Here We start the remaining counter at 10, and decrement it by 2 each pass through the loop. Once it goes negative, we end the loop.
fn main() { let mut remaining = 10; // Continue looping while a condition is true. while remaining >= 0 { println!("{}", remaining); // Subtract 2. remaining -= 2; } }
10 8 6 4 2 0
Reverse. To loop in reverse, we can get the iterator with iter() and then call rev(). This starts at the last element, and proceeds to the first.
fn main() { let items = vec![10, 20, 30, 40]; // Loop over items in reverse. for item in items.iter().rev() { println!("ITEM: {item}"); } }
ITEM: 40 ITEM: 30 ITEM: 20 ITEM: 10
For chars. In programs we often need to iterate over every character in a string. With for, we can do this in Rust—we can avoid some bugs easily this way.
Loop, String Chars
Usize indexes. Suppose we are looping over a range of i32 values, but want to access a Vec or slice with the value. We must cast to a usize in Rust.
A brief summary. For-loops are clear and easy-to-use in Rust. One important trick is the inclusive end value in range—the equals sign is part of the range.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 10, 2023 (simplify).
© 2007-2024 Sam Allen.