RustArena

Step 1 of 7

if, else if and else

Programs make decisions. if runs a block of code only when a condition is true, and else gives the alternative:

fn main() {
    let temperature = 31;
    if temperature > 30 {
        println!("Hot: stay in the shade");
    } else if temperature > 15 {
        println!("Pleasant");
    } else {
        println!("Bring a jacket");
    }
    println!("Forecast done");
}
Hot: stay in the shade
Forecast done

Comparison operators

You met these in the Types module; now they drive decisions:

Operator Meaning
== equal
!= not equal
< and > less than, greater than
<= and >= less or equal, greater or equal

Combine conditions with && (and), || (or) and ! (not): if age >= 18 && has_ticket { ... }.

Conditions must be bools

fn main() {
    let lives = 3;
    if lives {
        println!("still alive");
    }
}
error[E0308]: mismatched types
 --> src/main.rs:3:8
  |
3 |     if lives {
  |        ^^^^^ expected `bool`, found integer

Unlike C, JavaScript or Python, Rust doesn't treat numbers as true or false. Write the comparison you mean: if lives > 0.

Order matters

Because the first true condition wins, put the most specific check first. This version is wrong: a score of 95 prints "pass", because score >= 50 is checked first and the second branch is never reached:

if score >= 50 {
    println!("pass");
} else if score >= 90 {
    println!("excellent");
}

Swap the two conditions and it works.

Common mistakes

Your task

Fill in the keywords so the program prints the right message for an hp of 12: above 50 is Healthy, above 10 is Low health!, anything else is Critical!. The program should print Low health!.

Challenge 2

Write the body of describe_temperature so it prints <celsius> is hot above 30, is warm above 20, is cool above 0, and is freezing otherwise. main already calls it four times; the program should print:

35 is hot
25 is warm
15 is cool
0 is freezing

Challenge 3

FizzBuzz, one number at a time. Write fizzbuzz(n) so it prints FizzBuzz if n is divisible by both 3 and 5, Fizz if it's divisible by 3, Buzz if it's divisible by 5, and the number itself otherwise. Watch the order of your checks. Expected output for the calls in main:

Fizz
Buzz
FizzBuzz
7

Next: if is an expression