Problem overview
This version stores a student's scores by subject. Instead of two vectors lined up by position, a dictionary maps each subject name to its score: Math 92, English 78, Science 85 and History 67. The program prints each subject with its letter grade, in alphabetical order of the subject:
English: C
History: D
Math: A
Science: B
The scale is the familiar one: 90 or more is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and below 60 an F. The previous version looped over a vector by position. Here the loop walks the dictionary itself.
Approach: a map that keeps its keys sorted
Rust's dictionary types are HashMap and BTreeMap, both in std::collections. A HashMap visits its entries in an unspecified order that can differ from one run to the next, so it can't promise alphabetical output. A BTreeMap keeps its keys sorted, and iterating over it yields the entries in key order. For text keys the order is alphabetical, which is exactly what the output needs, with no sorting step in the program.
The program inserts the four subjects in the order Math, English, Science, History. Insertion order doesn't matter: the map puts them in order itself. A loop over the map then gives each subject together with its score, and the loop body is the grading ladder from before, checking from the top grade down.
The first entry the loop reaches is English, whose score is 78. The test for 90 fails, then 80 fails, then 70 succeeds, so English gets a C. The loop moves on to History (67, a D), Math (92, an A) and Science (85, a B). That matches the four lines above.
Step by step
- Create the map with
let mut grades = BTreeMap::new();. It needsmutbecause inserting changes it. - Insert Math and English with
insert, which takes the key first and the value second. - Insert Science and History the same way.
- Loop over the map with
for (subject, score) in &grades. The pair pattern splits each entry into its key and value, and the&borrows the map so it is still usable after the loop. - Declare
gradewithout a value inside the loop. The ladder will assign it. - Open the ladder with
if *score >= 90, assigning"A". - Add the
else ifbranches for 80, 70 and 60, assigning"B","C"and"D". - Close with
else, assigning"F", so every path setsgrade. - Print inside the loop the subject, a colon and a space, and the grade. That gives one line per subject.
The solution in Rust
let mut grades = BTreeMap::new();
grades.insert("Math", 92);
grades.insert("English", 78);
grades.insert("Science", 85);
grades.insert("History", 67);
for (subject, score) in &grades {
let grade;
if *score >= 90 {
grade = "A";
} else if *score >= 80 {
grade = "B";
} else if *score >= 70 {
grade = "C";
} else if *score >= 60 {
grade = "D";
} else {
grade = "F";
}
println!("{}: {}", subject, grade);
}
Rust details worth knowing:
- The import.
BTreeMaplives instd::collections, and a program that names it needsuse std::collections::BTreeMap;at the top of the file. Without it the compiler reportsuse of undeclared type `BTreeMap`. - Inferred types. The map's types come from the inserts: keys are
&strand values arei32. Nothing is annotated. - Why
*score. Looping over&gradesyields references:scoreis an&i32, not ani32. Writingscore >= 90is a type error (mismatched types, because a reference is compared with a number). The*reads the number behind the reference. - Borrowing keeps the map alive. Looping over
gradeswithout the&moves the map into the loop, and using it afterwards is an error (borrow of moved value: `grades`). With&gradesthe map can still be used after the loop. - Key order is byte order. Strings compare byte by byte, so every uppercase letter sorts before every lowercase one. A map with the keys
art,ZoologyandBiologyiterates asBiology,Zoology,art.
Complexity
Time: O(n log n) for n subjects in total. Each insert into a BTreeMap costs O(log n), and the loop that follows visits each entry once in O(n). The grading itself takes constant time per entry. Space: O(n) for the map.
Edge cases and common mistakes
- Inserting a key twice. A second
insertwith the same key replaces the value. Aftergrades.insert("Math", 50),insertreturnsSome(92), the old value, andgrades.get("Math")givesSome(50). The map still has four subjects. - An empty map. The loop body never runs and nothing is printed.
- A missing key.
grades.get("Art")returnsNoneand doesn't panic, because lookups on a map give anOption. - Boundaries. A score of exactly 90 is an A and 59 is an F. The ladder uses
>=, so each boundary belongs to the higher grade. - Using a
HashMapby habit. The code would look almost the same, but the lines could come out in a different order each time the program runs, and the lesson's tests expect the alphabetical order. - Expecting insertion order. The output starts with English, although Math was inserted first. Sorted key order is the whole point of this map type.
Testing
- The lesson's data prints
English: C,History: D,Math: AandScience: B. - An empty
BTreeMapprints nothing.
