Control Flow

Rust by example - Control flow

If Else

fn main() {
    let number = 3;
    // Note that `if` is an expression.
    let result: u8 = if number < 5 {
        println!("Condition was true");
        // The value of the `if` expression is the value of the last expression
        // in the block.
        5
    } else {
        println!("Condition was false");
        6
    };
    println!("{}", result);
}

Also else if <cond> { ... }

Loop

/// Demonstrates the use of a `loop` with a `break` statement to return a value.
fn main() {
    // Initialize a mutable counter.
    let mut counter = 0;

    // The `loop` keyword creates an infinite loop.
    // Note that it is an expression.
    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
            // The value passed to `break` is returned by the loop.
            // `continue` and loop labels also exist.
            // See https://doc.rust-lang.org/book/ch03-05-control-flow.html
        }
    };
    println!("{}", result);
}

While

/// This is an example of a while loop.
fn main() {
    // Initialize a mutable variable.
    let mut number = 5;
    // The loop continues as long as the condition is true.
    while number != 0 {
        println!("{number}!");
        // Decrement the number.
        number -= 1;
    }
}

For

fn main() {
    // Iterate over an array.
    let a = [10, 20, 30, 40, 50];
    for element in a {
        println!("the value is: {element}");
    }

    // Range - generates all numbers in sequence
    // starting from one number and ending before another number.
    for number in (1..4).rev() {
        // Use `rev` for reverse enumeration.
        println!("{number}!");
    }
}

Related Topics

  • Match.
  • Rust Patterns.