Rust, Software Development

Rust – How to Create While and For Loops

Rust lang

In Rust, there are three ways to create loops – using the loop, while, and for.

Using loop

loop is an endless loop and can only be terminated inside its block using break, or when an exception is thrown from within.



Return value from loop

loop can return a value using the break keyword. For example, we want to determine the sum of numbers 1 to 20:


Note that this feature is only available to loop. Trying to use break the same way in while or for results to compile-time errors.

Using while

The while loop is one of the most familiar constructs to anyone coming from Java, C/C++, C#, and other similar languages. The loop has a condition that is checked before an iteration takes place.


Using for

for loop is like a “for-each” loop that uses an iterator as its “data source”. It has the following syntax where expression represents an iterator.


Loop through a range of values


Loop through an array


Loop through a collection


You Might Also Like