Rust Fundamentals · 10 XP Pro

if and else

if runs a block only when its condition is true. The condition must be a bool: Rust never treats numbers or strings as truthy. Chain extra cases with else if, and finish with else as the catch-all.

let temp = 18;
if temp < 10 {
    println!("coat");
} else if temp < 20 {
    println!("jumper");
} else {
    println!("t-shirt");
}

In Rust, if is an expression: it produces a value. Every branch must give the same type, and you leave off the semicolon on the value you want to hand back.

let label = if temp < 15 { "cool" } else { "warm" };

Because a function body is also an expression, an if chain can be the last thing in a function with no return at all.

Your task

  1. Write ticket_price(age: u32) -> u32. Under 5 years old is free (0), ages 5 to 12 pay 8, ages 13 to 64 pay 15, and 65 or older pay 10.
  2. Write larger(a: i32, b: i32) -> i32 that returns the bigger of the two using an if expression (do not use max).

Next lesson →

Sign in to run your code. It's free.