This post shows how to create and use loops in Rust. There are three ways to create loops in Rust – using the loop, while, and for keywords.
The Endless Rust Loop Using the loop Keyword
To create an endless loop in Rust, we use the loop keyword. The loop keyword creates a loop that only a break statement or an exception can break from its block. The loop will run forever if we don’t have conditional statements within it to break the iteration. Similarly, an error or exception will stop the endless loop. Consider the following example Rust codes. The codes use the loop keyword while checking for a condition to break out of the infinite loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | fn main() { let mut i = 0; loop { i = i + 1; println!("Hello world! {}", i); if i >= 20 { break; } else { continue; } } println!("Loop completed!"); } |
The codes generate the following results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | Hello world! 1 Hello world! 2 Hello world! 3 Hello world! 4 Hello world! 5 Hello world! 6 Hello world! 7 Hello world! 8 Hello world! 9 Hello world! 10 Hello world! 11 Hello world! 12 Hello world! 13 Hello world! 14 Hello world! 15 Hello world! 16 Hello world! 17 Hello world! 18 Hello world! 19 Hello world! 20 Loop completed! |
If we omit the if-else statements, our codes will run forever.
Sometimes we want to return a value when the endless Rust loop terminates. We can do so by tweaking our codes a little bit using other Rust keywords. Consider the following codes. The loop can return a value using the break keyword. For example, we want to determine the sum of numbers 1 to 20.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | fn main() { let mut i = 0; let mut sum_tmp = 0; let sum:i32 = loop { i = i + 1; sum_tmp = sum_tmp + i; if i >= 20 { break sum_tmp; } }; println!("Sum:{}", sum); } |
The codes generate the following result.
1 | Sum:210 |
Note that this feature is only available to loop. Trying to use break the same way in a while or for results to compile-time errors.
Rust Loop Using the while keyword
The while loop is one of the most familiar constructs to anyone coming from Java, C/C++, C#, and other similar languages. The while loop has a condition that is checked before an iteration takes place. Unlike the Rust loop keyword, we cannot use the let keyword to return and assign a value to a variable.
1 2 3 4 5 6 7 8 9 10 11 12 | fn main() { let mut i = 0; while i < 20 { println!("i={}", i); if i == 10 { break; } i = i + 1; } } |
We get the following output.
1 2 3 4 5 6 7 8 9 10 11 | i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10 |
Loop Using the for keyword
The Rust for loop is like a “for-each” loop that uses an iterator as its “data source.” Therefore, it has the following syntax where expression represents an iterator.
1 2 3 | for var in expression { code } |
Consider the following examples. To loop through a range of values, we create codes as follows.
1 2 3 | for i in 0..5 { println!("{}", i); } |
Then, we get the result like this:
1 2 3 4 5 | 0 1 2 3 4 |
To loop through an array, we need to change our codes a little bit.
1 2 3 4 5 | let my_ints = [20, 40, 60, 80, 100]; for (i, my_int) in my_ints.iter().enumerate() { println!("my_ints[{}] = {}", i, my_int); } |
The codes generate the following result.
1 2 3 4 5 | my_ints[0] = 20 my_ints[1] = 40 my_ints[2] = 60 my_ints[3] = 80 my_ints[4] = 100 |
Lastly, to loop through a collection, we use the iterator instance from the compound type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | let mut vec:Vec<i32> = Vec::new(); vec.push(300); vec.push(600); vec.push(900); for my_int in vec.iter() { println!("{}", my_int); } println!("==="); for (i, my_int) in vec.iter().enumerate() { println!("my_ints[{}] = {}", i, my_int); } |
These codes display the following output.
1 2 3 4 5 6 7 | 300 600 900 === my_ints[0] = 300 my_ints[1] = 600 my_ints[2] = 900 |
We tested the codes using Rust 1.52.1.