🎓 A1Learner
🔍

Rust If..Else

Rust if..else is a choice between two blocks of code. The if block runs when a condition is true, and the else block runs when the condition is false.

Run a block when the condition is true

The block in braces runs only when the condition is true:

let age = 20;
if age >= 18 {
    println!("You can vote");
}

else covers the other case

When the condition is false, the else block runs instead:

let age = 15;
if age >= 18 {
    println!("You can vote");
} else {
    println!("Too young to vote");
}

Test more cases with else if

Chain more tests with else if. Rust stops at the first one that is true:

let temp = 25;
if temp > 30 {
    println!("Hot");
} else if temp > 20 {
    println!("Warm");
} else {
    println!("Cold");
}

The condition must be a bool

There are no round brackets around the condition, and a plain number is not a condition:

let number = 1;
// if number { } // error: expected bool, found integer

if can give a value

The whole if..else can produce a value, and you can save it in a variable:

let n = 7;
let label = if n % 2 == 0 { "even" } else { "odd" };
println!("{} is {}", n, label);

Example

fn main() {
    let score = 82;
    let grade = if score >= 90 { "A" } else if score >= 80 { "B" } else { "C" };
    println!("grade = {}", grade);
}

Key points

  • Less than: a < b.
  • Less than or equal: a <= b
  • Greater than: a > b.
  • Greater than or equal: a >= b
  • Equal to: a == b.
  • Not equal to: a != b

In this example, score is 82. Rust tests the conditions from the top. Is 82 >= 90? No. Is 82 >= 80? Yes, so the value "B" is chosen. The whole if..else if..else is one expression, and its value is saved in grade. The println! then prints grade = B. Every branch must give the same type. Here all three give text. So the compiler knows grade is always one clear thing.

Note

Unlike many other languages, if..else in Rust is an expression: it can produce a value and save it in a variable.

There is no need for a separate ?: operator.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why does if 1 { println!("hi"); } fail in Rust?