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:
ifin 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
elsewhen 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
ifexpressions to variables - Note the semicolon after the closing brace — this makes it a statement
- This pattern foreshadows
matchexpressions, which are cleaner for multiple cases
💡 Hint: This exercise mentions we’ll learn
enumfor better pattern matching later!