Conditional Statements
# 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 standardif/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, andelseblocks.
- Understand that conditions must be strict booleans.
-
Use
ifas an Expression to assign values.
-
Use the
matchstatement for powerful control flow.
3. The if Statement
An if expression allows you to branch your code depending on conditions.
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).
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).
*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.
Why match is awesome:
-
1.
Exhaustive: The compiler forces you to handle *every possible outcome*. If
errorcodeis an integer, you must provide a catch-allto handle numbers like999. If you forget, the code will not compile!
-
2.
Returns Values: Just like
if,matchis an expression and can return values to variables!
6. Mini Project: Grade Calculator
Let's build a program that assigns a letter grade based on a score.7. Common Mistakes
-
Missing the catch-all
inmatch: If you write amatchstatement for an integer and don't include=>, the compiler will throw an error saying "patternnot 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
matchoverelse if: If you are checking the same variable against 3 or more distinct values, amatchstatement is cleaner, faster, and safer due to compiler exhaustiveness checking.
9. Exercises
-
1.
Write an
if/elsestatement that checks if a variableageis greater than or equal to 18.
-
2.
Rewrite the logic using a
matchexpression with ranges (18..=150 => ...) to determine ticket prices (Child, Adult, Senior).
10. MCQs with Answers
In Rust, an if condition must evaluate to what data type?
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.
If an if block returns an i32, the else block must return:
What is the equivalent of a switch statement in Rust?
What does the (underscore) represent in a match block?
Why is match considered safer than standard if/else chains?
What syntax is used to match a range of numbers inclusive of the highest value?
Do the arms of a match block need a semicolon at the end of their logic?
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
matchstatement 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, thematch 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 usingloop, while, and for.