Skip to main content
Rust Programming
CHAPTER 07 Beginner

Conditional Statements

Updated: May 18, 2026
5 min read

# CHAPTER 7

Conditional Statements

1. Chapter Introduction

If programs could only execute from top to bottom, they would be very limited. To build intelligent applications, the code must make decisions based on changing conditions. In this chapter, we will learn how to use standard if/else statements, explore how to use if as an expression to assign variables, and introduce Rust's legendary match statement.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use if, else if, and else blocks.
  • Understand that conditions must be strict booleans.
  • Use if as an Expression to assign values.
  • Use the match statement for powerful control flow.

3. The if Statement

An if expression allows you to branch your code depending on conditions.
rust
1234567891011
fn main() {
    let number = 7;

    if number < 5 {
        println!("The number is small.");
    } else if number == 7 {
        println!("The number is exactly 7.");
    } else {
        println!("The number is big.");
    }
}

Strict Booleans Only! In languages like JavaScript or Python, you can write if (number). If the number is not 0, it is treated as "truthy". Rust does NOT do this. The condition MUST evaluate to a strict bool (true or false).

rust
123456789
let number = 3;

// ERROR: expected `bool`, found integer
// if number { println!("Number exists"); } 

// CORRECT:
if number != 0 {
    println!("Number exists");
}

4. Using if in a let Statement (Expression)

Remember Chapter 5? Because if is an expression, we can use it on the right side of a let statement to assign an outcome to a variable! (This replaces the Ternary Operator ?: found in C/Java).
rust
123456789101112
fn main() {
    let is_vip = true;
    
    // The if expression returns a value directly into 'price'
    let price = if is_vip {
        50 // Notice: no semicolon!
    } else {
        100 // Notice: no semicolon!
    };

    println!("Your ticket price is ${}", price);
}

*Rule: Both the if block and the else block MUST return the exact same data type. You cannot return an integer in one and a string in the other.*

5. The Power of match

If you have a long chain of else if statements, the code becomes hard to read. Rust provides a control flow operator called match (similar to a switch statement in other languages, but vastly more powerful).

match compares a value against a series of patterns and executes code based on which pattern matches.

rust
1234567891011
fn main() {
    let error_code = 404;

    match error_code {
        200 => println!("OK: Success!"),
        403 => println!("Forbidden: You do not have access."),
        404 => println!("Not Found: The page is missing."),
        500 => println!("Server Error: Something broke."),
        _ => println!("Unknown error code."), // The '_' is a catch-all (default)
    }
}

Why match is awesome:

  1. 1. Exhaustive: The compiler forces you to handle *every possible outcome*. If errorcode is an integer, you must provide a catch-all to handle numbers like 999. If you forget, the code will not compile!
  1. 2. Returns Values: Just like if, match is an expression and can return values to variables!

rust
12345678
let day_num = 3;
let day_name = match day_num {
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    _ => "Weekend",
};
println!("Today is {}", day_name);

6. Mini Project: Grade Calculator

Let's build a program that assigns a letter grade based on a score.
rust
12345678910111213141516171819
use std::io;

fn main() {
    println!("Enter your test score (0-100):");
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed");
    
    let score: u32 = input.trim().parse().expect("Not a number");

    let grade = match score {
        90..=100 => "A", // ..= means an inclusive range from 90 to 100!
        80..=89 => "B",
        70..=79 => "C",
        0..=69 => "F",
        _ => "Invalid Score",
    };

    println!("Your grade is: {}", grade);
}

7. Common Mistakes

  • Missing the catch-all in match: If you write a match statement for an integer and don't include =>, the compiler will throw an error saying "pattern not covered".
  • Mismatched return types: When using let x = if condition { 5 } else { "hello" };, the compiler will panic because a variable can only have one rigid data type.

8. Best Practices

  • Prefer match over else if: If you are checking the same variable against 3 or more distinct values, a match statement is cleaner, faster, and safer due to compiler exhaustiveness checking.

9. Exercises

  1. 1. Write an if/else statement that checks if a variable age is greater than or equal to 18.
  1. 2. Rewrite the logic using a match expression with ranges (18..=150 => ...) to determine ticket prices (Child, Adult, Senior).

10. MCQs with Answers

Question 1

In Rust, an if condition must evaluate to what data type?

Q2. Does Rust support "truthy" values like if 1 { ... }? a) Yes b) No Answer: b) No.

Q3. Can an if block be used on the right side of an equals sign (let x = if...)? a) Yes, because it is an expression b) No, because it is a statement Answer: a) Yes, because it is an expression.

Question 4

If an if block returns an i32, the else block must return:

Question 5

What is the equivalent of a switch statement in Rust?

Question 6

What does the (underscore) represent in a match block?

Question 7

Why is match considered safer than standard if/else chains?

Question 8

What syntax is used to match a range of numbers inclusive of the highest value?

Question 9

Do the arms of a match block need a semicolon at the end of their logic?

Q10. Does Rust have a ternary operator (condition ? trueval : falseval)? a) Yes b) No, you use an if/else expression instead Answer: b) No, you use an if/else expression instead.

11. Interview Questions

  • Q: Explain why Rust does not have truthy/falsy values for non-boolean types.
  • Q: Describe how "Exhaustiveness Checking" in a match statement prevents bugs in production.

12. FAQs

  • Can I match on strings? Yes! match mystring.asstr() { "yes" => ..., "no" => ..., _ => ...} works perfectly.

13. Summary

Controlling program flow is heavily fortified in Rust. By requiring strict booleans, Rust eliminates bugs caused by accidental "truthy" assignments. By utilizing expressions, developers can write incredibly concise assignments. Finally, the match statement acts as a strict, exhaustive router, ensuring your code handles every edge case before it even compiles.

14. Next Chapter Recommendation

Making a decision once is useful, but often we need to do things hundreds of times. In Chapter 8: Loops in Rust, we will explore how to repeat code execution using loop, while, and for.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·