Problem overview
A class has four students, and their names and scores sit in two vectors: names holds Alice, Bob, Carol and Dan, and scores holds 92, 78, 85 and 67. The score at position 0 belongs to the name at position 0, and so on. The program prints one line for each student with a letter grade:
Alice: A
Bob: C
Carol: B
Dan: D
The scale is the one from the previous version: 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. What is new here is that the same decision is made once per student, inside a loop.
Approach: one index, two vectors
Rust has no built-in link between the two vectors, so the program connects them by position. A loop counts i from 0 up to, but not including, names.len(). For each i, names[i] is the student and scores[i] is that student's score.
Inside the loop the program picks a grade with the same if/else-if ladder as before, checking from the top grade down so each later test needs only a lower bound. Then it prints the name and the grade. Because the print is inside the loop, it runs once per student, which produces the four lines.
One new Rust feature appears: let grade; with no value. The variable is declared first and given its value later, in the ladder. This works without mut because each pass through the loop creates a new grade, and the ladder assigns it exactly once.
Step by step
- Create
nameswithvec!, in the order Alice, Bob, Carol, Dan. - Create
scoreswith 92, 78, 85 and 67, in the same order so the positions line up. - Start the loop with
for i in 0..names.len(). The range excludes its end, soitakes the values 0, 1, 2 and 3. - Read the score at position
iintoscore, so the ladder tests a short name. - Declare
gradewithout a value. The ladder will fill it in. - Open the ladder with an
iffor 90 or more, assigning"A". - Add
else iffor 80 or more, assigning"B". - Add
else iffor 70 or more, assigning"C". - Add
else iffor 60 or more, assigning"D". - Close with
else, assigning"F". With this branch, every path givesgradea value. - Print inside the loop, after the ladder, the name at position
i, a colon and a space, and the grade, using two{}placeholders.
The solution in Rust
let names = vec!["Alice", "Bob", "Carol", "Dan"];
let scores = vec![92, 78, 85, 67];
for i in 0..names.len() {
let score = scores[i];
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!("{}: {}", names[i], grade);
}
Rust details worth knowing:
- Indexes are
usize. The range0..names.len()producesusizevalues, which is what vector indexing requires. Ani32variable can't index a vector:names[i]withi: i32is a compile error saying the slice cannot be indexed byi32. - Delayed initialization. The compiler checks that every path reaches an assignment before
gradeis used. If the finalelseis removed, the program doesn't compile: the error readsused binding `grade` is possibly-uninitialized. - Out-of-range indexing panics. A vector gives no default value for a missing position. Reading past the end stops the program with
index out of bounds. - Element types.
scoresbecomes aVec<i32>, because the comparisons with literals don't say otherwise andi32is the default integer type.namesis aVec<&str>.
Complexity
Time: O(n) for n students. The loop visits each position once, and each visit does a fixed number of comparisons. Space: O(1) extra, apart from the two input vectors, because the loop keeps only i, score and grade.
Edge cases and common mistakes
- Boundaries. For scores 90, 59 and 60, the program prints A, F and D.
- No students. With two empty vectors the range
0..0is empty, so the loop doesn't run and nothing is printed. - A vector that is too short. With two names and only one score, the first line prints
Ann: Aand the second pass panics withindex out of bounds: the len is 1 but the index is 1. The loop followsnames.len(), so the vectors must have the same length. - Looping one step too far.
0..=names.len()includes the length itself, andnames[names.len()]panics withindex out of bounds. Use the half-open range0..names.len(). - Printing outside the loop. A print after the closing brace wouldn't compile, because
gradeandiexist only inside the loop. The print has to sit in the loop body to run once per student. - Mixing up the vectors. Writing
names[i]where the score belongs gives a type error at compile time, since a name is text and the comparison needs a number.
Testing
- The lesson's data prints
Alice: A,Bob: C,Carol: BandDan: D, one per line. - Names Eve, Finn and Gus with scores 90, 59 and 60 print
Eve: A,Finn: FandGus: D. - Two empty vectors print nothing.
