Rust Tutorial menu

Rust Control Flow: if, match and Loops

Control flow decides which code runs and how many times.

Operators First

Rust uses the usual operators: + - * / % for maths, == != > < >= <= for comparison, and these for logic:

  • && (and): both sides true
  • || (or): at least one side true
  • ! (not): reverses true and false

Dividing two integers drops the decimal: 7 / 2 is 3.

if and else

The condition must be a bool. Rust will not treat a number as true or false.

Example

rust
fn main() {
    let marks = 58;

    if marks >= 80 {
        println!("Grade A");
    } else if marks >= 50 {
        println!("Pass");
    } else {
        println!("Fail");
    }
}
Output
Pass

if as an Expression

if gives back a value, so you can use it on the right side of let. Both branches must have the same type.

Example

rust
fn main() {
    let age = 16;
    let ticket = if age < 18 { 200 } else { 500 };
    println!("Ticket price: Rs {}", ticket);
}
Output
Ticket price: Rs 200

match

match compares a value against patterns. It must cover every possible case, so the compiler warns you if you forget one. _ matches anything.

Example

rust
fn main() {
    let day = 5;
    let name = match day {
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 | 7 => "Weekend",
        _ => "Invalid",
    };
    println!("{}", name);

    let marks = 73;
    match marks {
        90..=100 => println!("Excellent"),
        70..=89 => println!("Good"),
        0..=69 => println!("Keep trying"),
        _ => println!("Invalid marks"),
    }
}
Output
Friday
Good

In a match arm, 6 | 7 means "6 or 7", and 70..=89 means every number from 70 to 89.

loop

loop repeats forever until you break. A break can also return a value:

Example

rust
fn main() {
    let mut savings = 0;
    let mut months = 0;
    let result = loop {
        savings += 4000;
        months += 1;
        if savings >= 15000 {
            break months;
        }
    };
    println!("Goal reached in {} months", result);
}
Output
Goal reached in 4 months

while

while runs as long as the condition is true:

Example

rust
fn main() {
    let mut count = 3;
    while count > 0 {
        println!("{}...", count);
        count -= 1;
    }
    println!("Go!");
}
Output
3...
2...
1...
Go!

for and Ranges

for goes through a range or a collection. It is the loop you will use most.

Example

rust
fn main() {
    for i in 1..4 {
        print!("{} ", i);
    }
    println!();

    for i in (1..=5).rev() {
        print!("{} ", i);
    }
    println!();

    let fruits = ["Mango", "Apple", "Banana"];
    for fruit in fruits {
        println!("I like {}", fruit);
    }

    for (i, fruit) in fruits.iter().enumerate() {
        if i == 1 {
            continue;
        }
        println!("{}: {}", i, fruit);
    }
}
Output
1 2 3 
5 4 3 2 1 
I like Mango
I like Apple
I like Banana
0: Mango
2: Banana
RangeValues
1..41, 2, 3 (end not included)
1..=41, 2, 3, 4 (end included)
(1..=4).rev()4, 3, 2, 1

Exercise

Exercise

What does the range 0..3 produce in a for loop?

Learn Rust with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp