Home » Rust Loop

Loops

If we want to execute the block of statements more than once, then loops concept comes under the role. A loop executes the code present inside the loop body till the end and starts again immediately from the starting.

Rust consists of three kinds of loops:


loop

The loop is not a conditional loop. It is a keyword that tells the Rust to execute the block of code over again and again until and unless you explicitly stop the loop manually.

Syntax of loop

In the above syntax, block statements are executed infinite times.

Flow diagram of loop:

Rust loop

Let’s see a simple example of infinite loop

Output:

Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  .  .  .  infinite times   

In this example, “Hello tutoraspire” is printed over and over again until and unless we stop the loop manually. Generally, “ctrl+c” command is used to terminate from the loop.

Termination from loops

The ‘Break’ keyword is used to terminate from the loop. If ‘break’ keyword is not used then the loop will be executed infinite times.

Let’s see a simple example

Output:

Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  Hello tutoraspire  

In the above example, i is a counter variable, and it is a mutable variable which conveys that the counter variable can be changed for the future use.


Next TopicRust While Loop

You may also like