Module 4 • Lesson 19

If, Else, and Branching

📚 7 min read💻 Free Course🦀 nixus.pro

If Expressions

fn main() {
    // if is an expression - returns a value
    let x = 10;
    let label = if x > 5 { "big" } else { "small" };
    println!("{}", label);

    // All branches must return same type
    let abs = if x >= 0 { x } else { -x };

    // else if chains
    fn grade(score: u8) -> &'static str {
        if score >= 90 { "A" }
        else if score >= 80 { "B" }
        else if score >= 70 { "C" }
        else if score >= 60 { "D" }
        else { "F" }
    }
    println!("{}", grade(85));

    // Short-circuit evaluation
    let v: Vec = vec![1, 2, 3];
    if !v.is_empty() && v[0] > 0 { println!("positive first"); }

    // Leap year example
    fn is_leap(year: u32) -> bool {
        year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
    }
    println!("{} {} {}", is_leap(2024), is_leap(1900), is_leap(2000));
}

🎯 Practice

  1. Write fn classify_triangle(a: f64, b: f64, c: f64) -> &str: "equilateral", "isosceles", "scalene", or "invalid"
  2. Write fn bmi_category(bmi: f64) -> &str with standard BMI ranges

🎉 Key Takeaways