Menu Close

Articles

Rust: Repetition

A repetition statement will cause a block of code to repeat several times. The repetitive statement can be a block of code or an expression. The number of times it will be repeated can be controlled by a condition. If the condition is never true the repetition can be infinite and that is a bad situation that must be avoided.

Simple Loop

This is the most simple repetition statement. We use only keyword “loop” and { … } to create a repetitive block. This will be repeated forever and the program will get stack in the loop. You can stop using CTRL+C. This is actually a logical error. Good programmers must avoid infinite loops at all cost.

Note: This example is not available to be run, it is rude to block the session.

Break

To avoid an infinite loop you must create a break using a conditional¬† stop.In the next example we create a control variable “i” that is declared outside of the loop and start with 1. Then you can increment this variable with +1 every iteration. You can use the relation operator “i > 3”. This loop will execute 3 times then will stop and program will terminate.

Note: In this example you can see comments ending the blocks? This is a good practice rule but is not mandatory. You can add comments for end of blocks whenever you have nested blocks to end the curly brackets nightmare.

Continue

You can use continue  keyword to start over. This will create a kind of shortcut that will skip all other statements and restart the loop. You can continue a loop from inside a nested block.

While loop

This is a repetitive block of code that is executed as long as one condition is true. When the condition become false the program continue with next statement after the loop block end. Now the problem is to create a condition expression that will become false. If the condition never become false we again can have an infinite loop.

Range loop

This kind of loop is created using keyword “for” and it has two usages: One is to iterate a specific number of times over a range of numbers. Second is to iterate over a collection of items:¬†array, vector, string or map/dictionary. The range in Rust is created using a range expression with .. operator. (1..10) will create one number and will assign it to “i” to create the control variable.

Example:

For each

This is the most useful loop that is actually the iterative loop. It will visit each item from a collection until the last element is visited. The peculiar thing specific to Rust is that we have to specify method “iter()” to get an iterator that is actually a function that can be used to fetch the next element.

To be continued in next article …