Rust Course

Rust If/Else, Loop, While, and For

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

If Expressions

In Rust, if is an expression, not just a statement — it can return a value:

let number = 7;

if number < 5 {
    println!("Small");
} else if number < 10 {
    println!("Medium");
} else {
    println!("Large");
}

// if as expression
let category = if number < 5 { "small" } else { "large" };
println!("{}", category);

Loop — infinite loop

let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2; // loop returns a value!
    }
};
println!("Result: {}", result); // 20

While loop

let mut n = 1;
while n < 100 {
    n *= 2;
}
println!("{}", n); // 128

For loop

// Iterate over a range
for i in 0..5 {
    println!("{}", i); // 0, 1, 2, 3, 4
}

// Inclusive range
for i in 1..=5 {
    println!("{}", i); // 1, 2, 3, 4, 5
}

// Iterate over a collection
let arr = [10, 20, 30, 40, 50];
for element in arr {
    println!("{}", element);
}

Match — powerful pattern matching

let coin = "quarter";
let value = match coin {
    "penny"   => 1,
    "nickel"  => 5,
    "dime"    => 10,
    "quarter" => 25,
    _         => 0, // catch-all pattern
};
println!("{} cents", value); // 25 cents