Control Flow
Easy
+2 pts
Intro to Rust
5/15
🎯 Python's if/elif/else and match (3.10+) handle branching:
def describe_temp(celsius):
if celsius >= 30:
label = "Hot"
elif celsius >= 15:
label = "Mild"
else:
label = "Cold"
match label[0]:
case "H": return "stay inside"
case "M": return "enjoy"
case _: return "bundle up"
Rust has the same constructs, but with a key difference: if and match are expressions. They return values:
let label = if celsius >= 30 {
"Hot"
} else if celsius >= 15 {
"Mild"
} else {
"Cold"
};
No ternary operator needed — if itself returns a value. Python's equivalent would be label = "Hot" if celsius >= 30 else ..., but Rust's version scales to any number of branches.
match: exhaustive pattern matching
Rust's match is more powerful than Python's structural match. The compiler requires you to handle every possible case:
match label.chars().next() {
Some('H') => "stay inside".to_string(),
Some('M') => "enjoy".to_string(),
_ => "bundle up".to_string(),
}
The _ wildcard catches everything else. If you forget a case, the compiler tells you — no silent fall-through, no missed branches.
Your Task
Implement grade_message(score: i32) -> String:
- Use
if/else if/elseto determine the grade: score >= 90→"Excellent"score >= 75→"Good"score >= 50→"Pass"-
Otherwise →
"Fail" -
Use
matchon the first character of the grade to return: 'E'→"Top"'G'→"Decent"'P'→"Basic"- Anything else →
"None"
Example
assert_eq!(grade_message(95), "Top");
assert_eq!(grade_message(78), "Decent");
assert_eq!(grade_message(52), "Basic");
assert_eq!(grade_message(10), "None");
Further Reading
- The Rust Book — Control Flow — if expressions, loops
- The Rust Book — The match Control Flow — exhaustive pattern matching
fn grade_message(score: i32) -> String {
// TODO:
// 1. Use if / else if / else to get "Excellent", "Good", "Pass", or "Fail"
// 2. Use match on the first letter to return:
// "Top", "Decent", "Basic", or "None"
todo!()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_top() {
assert_eq!(grade_message(95), "Top");
}
#[test]
fn test_decent() {
assert_eq!(grade_message(78), "Decent");
}
#[test]
fn test_basic() {
assert_eq!(grade_message(52), "Basic");
}
#[test]
fn test_none() {
assert_eq!(grade_message(10), "None");
}
}
Topics