Build a grade report
Quick answer
Combine collections, validation and error propagation into a small report generator. Accept only integer grades from zero through twenty, reject invalid input, and keep the result deterministic.
Design before implementation
Separate parsing from aggregation. Define empty input as an error so the average has a nonzero denominator. Parse grades as u32, validate range, and sum in u64 for this small teaching dataset. The second example reports a rejected input without displaying a compiler-dependent diagnostic.
fn average(grades: &[u32]) -> Result<f64, &'static str> { if grades.is_empty() { return Err("empty"); } let mut total = 0u64; for &grade in grades { if grade > 20 { return Err("out of range"); } total += u64::from(grade); } Ok(total as f64 / grades.len() as f64)}fn main() { println!("{:.1}", average(&[12, 16, 20]).unwrap()); }Expected stdout (not executed):
16.0The fixed valid fixture permits unwrap here; ordinary callers should handle Err.
fn parse(input: &[&str]) -> Result<Vec<u32>, &'static str> { let mut grades = Vec::new(); for s in input { let n: u32 = s.parse().map_err(|_| "invalid number")?; if n > 20 { return Err("out of range"); } grades.push(n); } Ok(grades)}fn main() { println!("{:?}", parse(&["14", "21"])); }Expected stdout (not executed):
Err("out of range")No partial report is returned.
Common mistake
Do not divide by zero for an empty class or silently skip bad grades.
Try it yourself
Combine the two functions, report a friendly error, and add cases for empty, zero, twenty and negative grades.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build a grade report — practice quiz
Choose one answer per question, then review the explanation.
A report has grades 8, 12, 16. What is their arithmetic mean?
Why reject an empty grade list before computing the average?
A grade parser accepts 23 as u32 in a 0–20 system. What is missing?