Rust, Software Development

Rust – How to Create While and For Loops

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.

The codes generate the following results.

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.

The codes generate the following result.

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.

We get the following output.

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.

Consider the following examples. To loop through a range of values, we create codes as follows.

Then, we get the result like this:

To loop through an array, we need to change our codes a little bit.

The codes generate the following result.

Lastly, to loop through a collection, we use the iterator instance from the compound type.

These codes display the following output.

We tested the codes using Rust 1.52.1.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like