Learn/Rust/15. Final project: gradebook
Lesson 15 of 15
Sign in

Rust, lesson 15

Final project: gradebook

Time to use the whole course at once. You will build a small gradebook for a teacher. It reads commands one per line, stores students and their scores, reports mistakes as errors without crashing, and prints sorted reports. Every piece is something you have already practised; the challenge is arranging them so the program stays easy to follow.

Design in layers

  1. Data: a Student struct and a Gradebook struct that owns all students.
  2. Operations: methods on Gradebook that change it and return Result<(), String>, so failures carry a message.
  3. Parsing: a function that turns one line into a call to an operation.
  4. Main loop: read lines, run each command, print any error, carry on.

Methods never print errors themselves; they return them. Only the main loop decides how an error is shown. That keeps each layer small and testable.

The data

2 exercises to try what you just read.

Exercise 1

Recording grades

Press Ctrl Enter or Check to test your code.

Exercise 2

Report card

Press Ctrl Enter or Check to test your code.

BTreeMap (lesson 13) keeps names and subjects sorted, so reports come out in order without an extra sorting step.

Operations that can fail

Look up with get_mut when you need to change something. It returns an Option, which ok_or_else turns into a Result with your message, and ? passes it on:

Notice the borrowing: name and subject are borrowed &strs, and only when the subject is stored does it become an owned String, because the map must own its keys.

Parsing a command

Collecting a line's words into a Vec<&str> lets you match on a slice pattern, checking the command name and the number of arguments in one go:

Each arm returns a Result, so the whole match is a Result the main loop can inspect with if let Err(e) = ....

Integer averages

To keep output exact, averages in this project are whole numbers rounded down: the sum of the scores divided by how many there are, using integer division.

Build it in two steps

The first exercise handles valid input only. The second starts from a working first version and adds error handling and one more command. Test with tiny inputs after every change.

Further reading

  • The Rust Book: An example program using structs
  • The Rust Book: Recoverable errors with Result
  • std::collections::BTreeMap
  • The Rust Reference: Slice patterns

Each input line is one command. Support three commands (all input in this exercise is valid):

  • student <name> adds a student with no scores.
  • score <name> <subject> <points> records a score, replacing any earlier score that student had for that subject.
  • report prints one line per student, sorted by name: <name>: <subject>=<points> <subject>=<points> ... avg <average>, with subjects sorted by name and the average rounded down. A student with no scores prints <name>: no scores. If there are no students at all, print (no students).

Sample input:

student zoe
student ari
score ari math 90
score ari art 75
score zoe math 60
report
score zoe math 81
report

Sample output:

ari: art=75 math=90 avg 82
zoe: math=60 avg 60
ari: art=75 math=90 avg 82
zoe: math=81 avg 81

Extend the gradebook. Commands:

  • student <name>, score <name> <subject> <points>, report: as before.
  • top <subject>: print top <subject>: <name> <points> for the student with the highest score in that subject (on a tie, the alphabetically first name).

When a command cannot be done, print error: <message> and change nothing:

ProblemMessage
first word is not a known commandunknown command "<word>"
wrong number of wordsusage: student NAME, usage: score NAME SUBJECT POINTS, usage: top SUBJECT or usage: report
adding a name that already existsstudent "<name>" already exists
scoring a name that does not existno student "<name>"
points not a whole number from 0 to 100bad score "<text>"
top for a subject nobody has a score inno scores for "<subject>"

Blank lines are ignored. When a score line has both an unknown student and a bad score, report the bad score.

Sample input:

Sample output:

use std::collections::BTreeMap;

struct Student {
    scores: BTreeMap<String, u32>, // subject -> points
}

struct Gradebook {
    students: BTreeMap<String, Student>, // name -> student
}
impl Gradebook {
    fn score(&mut self, name: &str, subject: &str, points: u32) -> Result<(), String> {
        let student = self
            .students
            .get_mut(name)
            .ok_or_else(|| format!("no student \"{name}\""))?;
        student.scores.insert(subject.to_string(), points);
        Ok(())
    }
}
let words: Vec<&str> = line.split_whitespace().collect();
match words.as_slice() {
    ["student", name] => book.add_student(name),
    ["report"] => { book.report(); Ok(()) }
    _ => Err(String::from("unknown command")),
}
student ari
student ari
score ari math 9O
score bo math 50
score ari math 90
top math
top art
grade ari
report
error: student "ari" already exists
error: bad score "9O"
error: no student "bo"
top math: ari 90
error: no scores for "art"
error: unknown command "grade"
ari: math=90 avg 90