Lab · Rust Programming
Lab: a college marks register with borrowing
The brief
A college keeps a register of marks for one subject. You write functions that read the marks through a shared reference and change them through a mutable one, trigger the borrow checker's E0502 on purpose and fix it, slice the first name out of a full name, and add the lifetime that error E0106 asks for.
Why it matters
References are how real Rust code passes data around without copying it: almost every function you write at work takes &str, &[T] or &mut T. The borrow checker errors E0502 and E0106 are the two you will meet most often after E0382, so learning to read and fix them calmly is time well spent.
Skills you practise
- &[u32] and &mut Vec<u32> parameters
- iter_mut and *
- error E0502
- copying a value out to end a borrow
- &str slices with find
- error E0106 and lifetime 'a
- chars().count() versus len()
You need
- Rust stable installed with rustup
- A terminal and an editor
What you will have at the end
A marks_register cargo project with borrowing functions, a first-name slice, a longer_name function with a lifetime, and the E0502 and E0106 messages you fixed.
How it is marked (rubric, 100 points)
| Correct outputTotals 289 and 299, topper 90, 6 students, the first names and both longer names are right. | 35 |
|---|---|
| Right kind of reference&[u32] and &str for reading, &mut only for give_grace, no clone() used to dodge the borrow checker. | 30 |
| Reads borrow errorsCan point to the three labels of E0502 and explain the help line of E0106. | 25 |
| Unicode careUses chars().count() for letters and never slices text with fixed byte numbers. | 10 |
0/5 steps done
Step 1 of 5
Read and change marks through references
The totals before and after grace marks are 289 and 299, and the Vec is still usable.
Create the project with cargo new marks_register. total takes &[u32]: a shared borrow, so it can read but not change, and main keeps ownership. give_grace takes &mut Vec<u32> and adds 5 to every mark below 35 (the pass mark). Loop with for m in marks.iter_mut(), and use *m to reach the number behind each reference. Call total(&marks), then give_grace(&mut marks), then total(&marks) again, and print the marks with {:?}.
$ cargo runYour notes: src/main.rs
Write down each command you ran. It goes into your project summary.