DEV Community

Cover image for What are Rust Loops ?
Mansoor Ahmed
Mansoor Ahmed

Posted on

What are Rust Loops ?

DESCRIPTION
Loops:
Loops execute a block of code more than once.

Types of loops
loop
while
for
loop
The loop keyword tells Rust to execute a block of code over and once again forever or until you explicitly tell it to prevent.
‘break’ expression can be used to stop the loop and the value is placed after the break expression that we want in return.
Example

fn main() {

loop {

println!(“again!”);

}

}

Result:

again!

again!

again!

again! (and so on …..)

Example

        fn main() {
Enter fullscreen mode Exit fullscreen mode

let mut counter = 0;

let result = loop {

counter += 1;

if counter == 10 {

break counter * 2;

}

};

println!(“The result is {}”,

result); }

Result:

        Here 20 will be save in the result variable
Enter fullscreen mode Exit fullscreen mode

While loop
In this type of loop While the condition is true, the loop runs. When the condition ceases to be true, the program calls break, stopping the loop.
Example

        fn main() {
Enter fullscreen mode Exit fullscreen mode

let mut number = 3;

while number != 0 {

println!(“{}!”, number);

number = number – 1;

}

println!(“LIFTOFF!!!”);

}

Result:

3!

2!

1!

LIFTOFF!!!

For loop
loops through a block of code a number of times(iteration)
Example

fn main() {

let a = [10, 20, 30, 40, 50];

for element in a.iter() {

println!(“the value is: {}”,

element);

}

}

Result:

the value is: 10

the value is: 20

the value is: 30

the value is: 40

the value is: 50

Note:

iter() is used for iteration.
Example

fn main() {

for number in (1..4).rev() {

println!(“{}!”, number);

}

println!(“LIFTOFF!!!”);

}

Result:

3!

2!

1!

LIFTOFF!!!

Note:

(1..4) is for declaring range.
rev() is used for reverse order
Comments
Comment makes code easy to understand when some time extra explanation is warranted.
Compiler will ignore to compile the comments in code but people reading the source code may find it useful.
Comments must start with two slashes and continue until the top of the road.
For comments that reach beyond one line, you’ll got to include // on each line.
Examples: Comments

        fn main( ) {
Enter fullscreen mode Exit fullscreen mode

// hello

// hi

// hey

}

fn main() {

// hello, world

}
For more details visit:https://www.technologiesinindustry4.com/2020/10/what-are-rust-loops.html

Discussion (0)