Rust · Chapter 19 of 26
Smart pointers
By the end of this chapter you can put a value on the heap with Box, build a type that contains itself, share one value between several owners with Rc, change a shared value with RefCell (and say when it panics), combine the two as Rc<RefCell<T>>, make your own type act like a reference with Deref, and run your own code when a value is freed, with Drop. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real programs
- 4 tasks
- Rust
- In the all labs plan
The first 2 chapters of Rust are free. This one comes with the all labs plan.
Why you need this
Three things the box needs do not fit the ownership you know.
Neha's price rules wrap one another. The winter rule at Kheda is the buffalo chart, plus 150 paise a litre, but never more than ₹45 a litre: a cap around a bonus around a chart. Next month there will be a rule around that. A Rule that holds a Rule cannot be written with what you know: the compiler refuses a type that contains itself, because it could never know its size.
At a big society like Karamsad, with 186 members, three counters open at once, and every counter must see one register of which boxes are open. Ownership (chapter 5) gives a value exactly one owner. References (chapter 6) let the counters look at it, but then the register must outlive every counter, and while anyone holds a & nobody can change it.
And when a shift closes, the box must write it down every time: at the end of the function, on an early return, on a ? that gives up. Writing "closed" by hand before each way out is how one gets missed.
Smart pointers are types that hold a value and add a rule of their own: Box puts it on the heap, Rc counts its owners, RefCell checks borrows while the program runs. Drop lets any type run code when it is freed.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
rule.rs: a price rule that wraps another
Rule is an enum: Chart(Kind) is that kind's rate chart, fat * fat_paise + snf * snf_paise from doodh::rate(kind); Bonus(paise, rule) is the inner rule's price plus paise; AtMost(paise, rule) is the inner rule's price, but never more than paise. The inner rule is in a Box.
Write the method per_litre(&self, fat: u32, snf: u32) -> u32, the paise a litre earns under the rule (fat and SNF in tenths of a percent). Chart(Cow) gives 2980 for fat 40 and snf 85; Bonus(150, Chart(Buffalo)) gives 4166 for fat 64 and snf 91; AtMost(3000, Chart(Cow)) gives 3000 for fat 42 and snf 86, and 2980 for fat 40 and snf 85. The Check also tries a bonus inside a bonus, a cap around a bonus, and 1,000 bonuses of 1 paise one inside the next around Chart(Cow) (3980 for fat 40 and snf 85).
Then write winter_rule() -> Rule: the buffalo chart, plus a bonus of 150 paise, the whole of it at most 4500 paise. It gives 4166 for fat 64 and snf 91, 3510 for fat 50 and snf 85, and 4500 for fat 85 and snf 95.
- Task 2
register.rs: a register every counter shares
The register of open boxes is an Rc<RefCell<Vec<String>>>, shared by every Counter. Write new_register(), an empty register. Counter::open(box_id: &str, register: &Rc<RefCell<Vec<String>>>) -> Counter adds box_id to the end of the register and keeps its own owner of that same register in its register field, with box_id in its box_id field. close(&self) takes its box_id out of the register (closing twice does nothing more). open_boxes(&self) returns a copy of the ids in the register, in the order they were opened.
The Check opens B2014, B2002 and B2120 on one register: it then holds ["B2014", "B2002", "B2120"] and has 4 owners (Rc::strong_count: the caller and the three counters). After B2002 closes, open_boxes() from another counter is ["B2014", "B2120"]. After the B2120 counter is dropped, the register has 3 owners. A counter opened on a second register sees only its own boxes.
- Task 3
shift.rs: a shift that records when it closes
ShiftGuard::open(society: &str, log: &Rc<RefCell<Vec<String>>>) -> ShiftGuard writes "S014 open" (with its society) into the log, and keeps its own owner of that same log; pour(&mut self) counts one can. Write Drop for ShiftGuard: when a guard is dropped it writes "S014 closed after 3 cans" into the log, with "1 can" for one can and "0 cans" for none. Print nothing: the Check reads the log.
The Check opens S014, pours 3 cans, and the log must be ["S014 open"] while the guard is alive and ["S014 open", "S014 closed after 3 cans"] after its scope ends. It opens S002 then S120 in one scope and pours one can at S002: the log must then be ["S002 open", "S120 open", "S120 closed after 0 cans", "S002 closed after 1 can"]. It opens S061, pours 12 cans, sees 2 owners of the log, calls drop on the guard, and the log must end with "S061 closed after 12 cans" at once, with 1 owner left.
- Task 4 · interview question
Interview: ledger.rs, the bonus that panicked
add_bonus(totals: &RefCell<BTreeMap<String, u64>>, threshold: u64, bonus: u64) -> usize adds bonus paise to every farmer whose total is at least threshold and returns how many got it. Lakhan's version compiles and panics with "RefCell already borrowed" as soon as one farmer qualifies. Fix it.
The Check starts with F10122 120000, F10377 80000, F10412 205000 and F10663 99999 paise: add_bonus with threshold 100000 and bonus 5000 returns 2 and leaves F10122 at 125000, F10412 at 210000 and the others unchanged, with the totals no longer borrowed. A threshold of 300000 returns 0 and changes nothing, and a second run with threshold 100000 returns 2 again.
Farhan will ask: when does a RefCell panic, and why could the compiler not catch it?
What you will learn
- Box<T>: a value on the heap, with one owner; recursive types; Box<dyn Trait>.
- Deref: why a Box works like the value inside it, and *.
- Rc<T>: several owners of one value; Rc::clone and Rc::strong_count.
- RefCell<T>: borrowing checked at run time, and the panic when the rules break.
- Rc<RefCell<T>>: a value shared and changed by several owners; Weak in a paragraph.
- Drop: code that runs when a value is freed, in a fixed order.
More in Real programs
Build "Smart pointers" yourself
DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Rust are free. This one comes with the all labs plan.