DEV Community

Hilary Omondi
Hilary Omondi

Posted on

LOOPS IN RUST

  1. Loops - The infinite Loop The loop keyword create an infinite loop.You must explicitly use break to exit.
 fn main() {
  let mut counter = 0;
   loop{
   counter += 1;
   println!("Counter = {}", counter);
    if counter == 3{
    break; // exits the loop
  }
 }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5

  1. While - Loop while a Condition is True
  • a while loop continues as long as a condition is true
fn main() {
 let mut number = 3;
 while number > 0 {
    println!("{}!", number);
    number -= 1;
}
 println!("LIFTOFF 🚀")
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT
3!
2!
1!
LIFTOFF 🚀

  1. for - Looping Through Ranges and Collections
  • The for loop is the most idiomatic in Rust
fn main() {
  for i in 1..5 {
  println!("i = {}", i);
}
}
Enter fullscreen mode Exit fullscreen mode

Output

i = 1
i = 2
i = 3
i = 4

Top comments (0)