Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flow Control

If

if expression:

#![allow(unused)]
fn main() {
let number = if condition {
    5
} else {
    6
};
}

if let expression:

#![allow(unused)]
fn main() {
let o = Some(3);
let v = if let Some(x) = o {
    x
} else {
    0
};
}

Loop

For

#![allow(unused)]
fn main() {
for i in 1..=5 {}
for _ in 0..10 {}
for item in collection {}
for item in &collection {}
for item in &mut collection {}
for (i, v) in collection.iter().enumerate() {}
}

While

fn main() {
    let mut n = 0;

    while n <= 5  {
        println!("{}!", n);
        n = n + 1;
    }
}

Expression

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);
}