If Exercises

Overview

These exercises cover conditional expressions, including using if as an expression rather than just a statement.


if1 - Basic Conditionals

Concept: Using if as an expression

fn bigger(a: i32, b: i32) -> i32 {
    if a > b { a } else { b }
}

Key Takeaways:

  • if in Rust is an expression — it returns a value
  • Both branches must return the same type
  • No parentheses needed around the condition (unlike C/Java)

if2 - Else If Chains

Concept: Multiple conditions with else if

fn picky_eater(food: &str) -> &str {
    if food == "strawberry" {
        "Yummy!"
    } else if food == "potato" {
        "I guess I can eat that."
    } else {
        "No thanks!"
    }
}

Key Takeaways:

  • Chain conditions with else if
  • Always include a final else when returning values (to cover all cases)
  • String comparison uses == on &str

if3 - Nested Conditionals

Concept: Using conditional results in subsequent logic

fn animal_habitat(animal: &str) -> &str {
    let identifier = if animal == "crab" {
        1
    } else if animal == "gopher" {
        2
    } else if animal == "snake" {
        3
    } else {
        4
    };
 
    if identifier == 1 {
        "Beach"
    } else if identifier == 2 {
        "Burrow"
    } else if identifier == 3 {
        "Desert"
    } else {
        "Unknown"
    }
}

Key Takeaways:

  • You can assign if expressions to variables
  • Note the semicolon after the closing brace — this makes it a statement
  • This pattern foreshadows match expressions, which are cleaner for multiple cases

💡 Hint: This exercise mentions we’ll learn enum for better pattern matching later!


Rust Book Reference