What are Rust Loops ?

 What are Rust Loops?

What are Rust Loops?

DESCRIPTION

Loops: 

  • Loops execute a block of code more than once.

Types of loops

  1. loop
  2. while
  3. for
  1. loop

Example

fn main() {

loop {

println!(“again!”);

}

}

Result:

again!

again!

again!

again! (and so on …..)

Example

            fn main() {

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

  1. While loop

Example

            fn main() {

let mut number = 3;

while number != 0 {

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

number = number – 1;

}

println!(“LIFTOFF!!!”);

}

Result:

3!

2!

1!

LIFTOFF!!!

  1. For loop

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( ) {

// hello

// hi

// hey

}

fn main() {

// hello, world

}

Leave a Comment