We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Ground Rules: Values, Types, Control Flow step 12 of 24
Return a grade with an if expression
Rewrite the supplied grading function as an if / else if / else
expression. Use the selected branch's value as the function result, without
a return statement or a temporary letter binding.
pub fn grade(score: u32) -> char
| Score | Grade |
|---|---|
| 90 or higher | 'A' |
| 80 through 89 | 'B' |
| 70 through 79 | 'C' |
| 60 through 69 | 'D' |
| Below 60 | 'F' |
Scores can be any u32, not just values up to 100. For example, 89 returns
'B', 90 returns 'A', and 150 also returns 'A'.
Use the value of the final expression
An if expression selects a branch and produces its value. When it is the
final expression in a function body, that value becomes the function result.
This smaller example returns a number:
fn sign_label(positive: bool) -> i32 {
if positive { 1 } else { -1 }
}
fn main() {
assert_eq!(sign_label(true), 1);
assert_eq!(sign_label(false), -1);
}
Apply the same structure to the grade thresholds. Check from highest to
lowest so an earlier branch does not catch a score intended for a higher
grade. Each selected branch should produce a char.
Why the semicolon matters
In fn value() -> i32 { 5 }, the final expression gives the block its value.
Writing fn value() -> i32 { 5; } instead discards that expression's value.
With no final expression, this block evaluates to (), the unit value, and
the function fails with E0308 because it promises an i32.
Leave off the semicolon after each grade literal and after the final if
expression. Semicolons are still correct for ordinary statements elsewhere;
the issue here is discarding the value the function needs to return.
Repairing the starter
The starter returns the right grades, but Clippy rejects its unnecessary late
initialization and final return (needless_late_init and needless_return).
Rust already checks that its letter variable is initialized before use.
The rewrite makes the selected value easier for a reader to follow.
Returning the if expression directly also avoids a binding used only to
return that same value, which can trigger let_and_return.
Use single-quoted literals such as 'A', whose type is char. The
double-quoted "A" is a string slice, not a char. The harness converts
your result into a one-character JSON string for display.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
Rust reference solution
Sign in to track your attempts toward unlocking the reference solution.