Rust, lesson 15
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.
Student struct and a Gradebook struct that owns all students.Gradebook that change it and return Result<(), String>, so
failures carry a message.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.
2 exercises to try what you just read.
BTreeMap (lesson 13) keeps names and subjects sorted, so reports come out in order without an
extra sorting step.
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.
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) = ....
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.
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.
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
reportSample output:
ari: art=75 math=90 avg 82
zoe: math=60 avg 60
ari: art=75 math=90 avg 82
zoe: math=81 avg 81Extend 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:
| Problem | Message |
|---|---|
| first word is not a known command | unknown command "<word>" |
| wrong number of words | usage: student NAME, usage: score NAME SUBJECT POINTS, usage: top SUBJECT or usage: report |
| adding a name that already exists | student "<name>" already exists |
| scoring a name that does not exist | no student "<name>" |
| points not a whole number from 0 to 100 | bad score "<text>" |
top for a subject nobody has a score in | no 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
reporterror: 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