Control Flow
Level: intro (score: 1)
🚀 These intro exercises are prep for our
Rust Intro Cohort Program.
🎯 Both Python and Rust support if
/elif
/else
(Python) or if
/else if
/else
(Rust). Both now also have a powerful match
expression for pattern matching.
Key differences for Pythonistas:
if
in Rust is an expression: it returns a value.match
lets you handle multiple patterns exhaustively.
✅ Your task:
Implement grade_message(score: i32) -> String
:
- If
score >= 90
, return"Excellent"
. - If
score >= 75
, return"Good"
. - If
score >= 50
, return"Pass"
. - Otherwise, return
"Fail"
.
Then use match
on the first letter of the result to:
- Return
"Top"
if it starts withE
"Decent"
ifG
"Basic"
ifP
"None"
otherwise
Return the final match
result.
💡 Hint:
if
/elif
/else
returns the value of the executed branch.match
must cover all cases (_
works as the fallback).
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");
pub 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"
}
#[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");
}
}