0

Rust – How to Create While and For Loops

In Rust, there are three ways to create loops – using 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.

Example:

Output

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:

Output

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 construct 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.

Output

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.

Examples

Loop through a range of values

Output

Loop through an array

Output

Loop through a collection

Output

Karl San Gabriel

Karl San Gabriel

Professional Software Developer