Box puts a value on the heap, Rc lets several owners share one value, RefCell lets you change a value behind a shared reference, and Weak breaks the cycles that would leak memory. This part shows each one, with the counts printed.
So far every value has had one owner, as Part 6 promised. Some data doesn’t fit that shape. A list whose items hold the rest of the list, a bank account that two cards share, a folder that knows its parent: each one needs a little help from the standard library.
This part covers four types that give that help: Box, Rc, RefCell and Weak, with a short look at Cell and Deref. They’re called smart pointers: a pointer to some data, plus a rule about who owns it and when it’s freed. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
Here’s a list of numbers. Each item holds a number and the rest of the list, and Nil marks the end. Does it compile?
#[derive(Debug)]
enum List {
Cons(i32, List),
Nil,
}
fn main() {
let list = List::Cons(1, List::Cons(2, List::Nil));
println!("{list:?}");
}
It doesn’t:
error[E0072]: recursive type `List` has infinite size
--> src/main.rs:2:1
|
2 | enum List {
| ^^^^^^^^^
3 | Cons(i32, List),
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
3 | Cons(i32, Box<List>),
| ++++ +
The compiler needs to know how many bytes a List takes, so it can put one on the stack. A Cons holds an i32 and a whole List. That List might be a Cons, which holds another whole List, and so on. There’s no end to the sum, so the size is infinite. (The compiler also prints a second error, E0391, about the same loop. Fix the first one and both go away.)
The help: line names the fix. “Indirection” means: don’t store the list inside, store a pointer to it. A pointer has a fixed size, however long the list behind it is.
Box: one value, on the heap
Box::new(value) moves a value onto the heap and gives you a Box<T> that owns it. The box itself is just a pointer:
use std::mem::size_of;
fn main() {
let on_stack = 5;
let on_heap = Box::new(5);
println!("on_stack + on_heap = {}", on_stack + *on_heap);
println!("i32: {} bytes", size_of::<i32>());
println!("Box<i32>: {} bytes", size_of::<Box<i32>>());
println!("[u8; 1000]: {} bytes", size_of::<[u8; 1000]>());
println!("Box<[u8; 1000]>: {} bytes", size_of::<Box<[u8; 1000]>>());
}
It prints:
on_stack + on_heap = 10
i32: 4 bytes
Box<i32>: 8 bytes
[u8; 1000]: 1000 bytes
Box<[u8; 1000]>: 8 bytes
On a 64-bit machine a box is 8 bytes, whatever it points at. The * in *on_heap follows the pointer to the value, the same * you used on references in Part 7.
A Box is an owner like any other. It has one owner at a time, it moves like a String, and when it’s dropped, it frees its heap memory. There’s no counting and no run-time check. It’s the plainest smart pointer.
That’s enough to fix the list:
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn sum(list: &List) -> i32 {
match list {
Cons(value, rest) => value + sum(rest),
Nil => 0,
}
}
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("{list:?}");
println!("sum = {}", sum(&list));
}
It prints:
Cons(1, Cons(2, Cons(3, Nil)))
sum = 6
Now a Cons holds an i32 and a pointer, so its size is fixed. Each item sits in its own heap allocation, and each box owns the next one. When list is dropped, the first box frees the second, which frees the third.
Notice sum(rest). rest is a &Box<List>, and sum wants a &List. Rust follows the box for us. That’s Deref at work, which we’ll come back to near the end.
Use Box when you need a recursive type, when a value is large and you want to move only a pointer, or for trait objects like Box<dyn Error>, which Part 12 used and Part 21 explains.
Rc: several owners of one value
Sometimes one value really has several owners, and none of them is clearly last. Two cards share one bank account. Two lists share the same tail. With Box, there can only be one owner.
Rc<T> (“reference counted”) allows many. Rc::new(value) puts the value on the heap next to a counter. Rc::clone(&rc) doesn’t copy the value. It makes a second pointer to the same allocation and adds 1 to the counter. Each time an Rc is dropped, the counter goes down by 1. When it reaches 0, the value is dropped and the memory is freed.
Rc::strong_count reads the counter, so we can watch it:
use std::rc::Rc;
struct Book(&'static str);
impl Drop for Book {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
let a = Rc::new(Book("Dune"));
println!("after a: strong = {}", Rc::strong_count(&a));
let b = Rc::clone(&a);
println!("after b: strong = {}", Rc::strong_count(&a));
println!("same book: {}", Rc::ptr_eq(&a, &b));
{
let c = Rc::clone(&a);
println!("after c: strong = {}", Rc::strong_count(&c));
}
println!("c's scope end: strong = {}", Rc::strong_count(&a));
drop(b);
println!("after drop(b): strong = {}", Rc::strong_count(&a));
println!("end of main, a reads {}", a.0);
}
It prints:
after a: strong = 1
after b: strong = 2
same book: true
after c: strong = 3
c's scope end: strong = 2
after drop(b): strong = 1
end of main, a reads Dune
drop Dune
Rc::ptr_eq says whether two Rcs point at the same allocation, and they do. There’s one Book, and drop Dune prints once, after the last owner is gone. The Drop trick is the one from Part 6.
The animation steps through the same program. As always in this series, the stack is on the left, the heap is on the right, and a solid arrow means “owns”.
Each Rc::clone adds an arrow and raises the count. Each drop removes one and lowers it. Only the last drop, at count 0, frees the Book.
Here are those steps in words, in case the animation doesn’t play for you:
let a = Rc::new(Book("Dune"))puts theBookon the heap, next to a strong count of 1.ais a pointer to it.let b = Rc::clone(&a)makes a second pointer to the same allocation. Nothing is copied on the heap. The count goes up to 2.- Inside the block,
let c = Rc::clone(&a)adds a third pointer, and the count is 3. - The block ends, so
cis dropped. Dropping anRclowers the count to 2. TheBookstays, because others still own it. drop(b)lowers the count to 1.- At the end of
main,ais dropped. The count reaches 0, so theBookis dropped and its memory is freed.
You can write a.clone() instead of Rc::clone(&a), and it does the same thing. The Rust book’s convention is Rc::clone(&a), so that a reader can see it’s the cheap kind of clone, a counter going up, and not a deep copy of the data.
What Rc won’t let you do
An Rc gives every owner shared access, so it acts like a &T. You can read through it, but you can’t change the value:
use std::rc::Rc;
fn main() {
let shared = Rc::new(vec![1, 2, 3]);
let other = Rc::clone(&shared);
other.push(4);
println!("{shared:?}");
}
It prints:
error[E0596]: cannot borrow data in an `Rc` as mutable
--> src/main.rs:6:5
|
6 | other.push(4);
| ^^^^^ cannot borrow as mutable
This is the “many readers or one writer” rule from Part 7. shared and other are two readers of the same vector. If other could push while some code held &shared[0], the push might move the items to a bigger buffer and leave that reference pointing at freed memory. To change shared data, we need one more piece.
RefCell: the borrow rules, checked while the program runs
RefCell<T> holds a value and lets you borrow it through a shared reference:
.borrow()gives you shared access, like&T;.borrow_mut()gives you changing access, like&mut T, even though you only have a&RefCell.
This is called interior mutability: the outside looks unchangeable, and the inside can change. The rules are still the rules from Part 7, many readers or one writer. What changes is when they’re checked. The compiler checks & and &mut before the program runs. A RefCell keeps a small counter of who’s borrowing right now and checks it each time you call borrow or borrow_mut.
use std::cell::RefCell;
fn main() {
let names = RefCell::new(vec![String::from("Ana")]);
names.borrow_mut().push(String::from("Ben"));
let r1 = names.borrow();
let r2 = names.borrow();
println!("{} names: {} and {}", r1.len(), r1[0], r2[1]);
}
It prints:
2 names: Ana and Ben
names isn’t mut, and we pushed into it anyway. The borrow_mut() on line 6 ended at the end of its statement, so two readers could borrow afterwards.
Break the rule and the program still compiles. It stops when it runs:
use std::cell::RefCell;
fn main() {
let scores = RefCell::new(vec![10, 20]);
let mut first = scores.borrow_mut();
let mut second = scores.borrow_mut();
first.push(30);
second.push(40);
println!("{:?}", scores.borrow());
}
It prints:
panicked at src/main.rs:7:29:
RefCell already borrowed
Line 7, column 29 is the second borrow_mut. The first one is still alive, because first is used on line 8. With plain &mut, this would be a compile error (E0499 from Part 7). With RefCell, it’s a panic: the program stops at run time with a message.
When you’d rather check than crash, try_borrow() and try_borrow_mut() return a Result instead of panicking. The error type for a failed try_borrow_mut is BorrowMutError.
Explain it like I’m ten
A family shares one TV. Nobody owns it alone. Every person who’s watching counts as one. When someone leaves the room, the count goes down. The last person to leave turns the TV off. That’s Rc: shared ownership, and the last owner cleans up.
Now the remote. Anyone in the room can look at the screen at the same time. But only one person may hold the remote, and only when nobody else is holding it. There’s no grown-up checking the rule before the evening starts. Instead, each time you reach for the remote, you check whether someone has it. If you grab it while your sister is holding it, the evening stops right there. That’s RefCell.
The precise version
Rc::new puts the value on the heap together with two counters: a strong count and a weak count (we’ll meet weak below). An Rc<T> is one pointer to that allocation, 8 bytes on a 64-bit machine. Rc::clone adds 1 to the strong count. Dropping an Rc subtracts 1. At strong count 0, the value is dropped. The allocation itself is freed once the weak count is 0 as well. These counters aren’t safe to change from two threads at once, so the compiler won’t let an Rc cross to another thread. Part 23 shows that error, and Part 24 uses Arc, the thread-safe version.
RefCell<T> stores the value next to a borrow state. borrow() returns a guard of type Ref<T>, and borrow_mut() returns a RefMut<T>. Each guard updates the state when it’s made and again when it’s dropped. That’s why a borrow lasts as long as its guard, not as long as the line. A conflicting borrow panics: “RefCell already borrowed” from borrow_mut, or “RefCell already mutably borrowed” from borrow. A RefCell can’t be shared between threads either; Part 24 uses Mutex for that.
Where the analogy breaks: nobody turns the TV off on purpose. Rust drops the value the moment the count reaches 0, with no extra code from you. And the “evening stops” part is real: a panic ends the program, not just the TV.
Rc and RefCell together
Rc gives you many owners who can only read. RefCell lets you change a value through a shared reference. Put one inside the other, Rc<RefCell<T>>, and you get many owners who can all change the same value, one at a time:
use std::cell::RefCell;
use std::rc::Rc;
struct Account {
balance: i64,
}
struct Card {
holder: &'static str,
account: Rc<RefCell<Account>>,
}
impl Card {
fn spend(&self, amount: i64) {
self.account.borrow_mut().balance -= amount;
println!("{} spends {amount}", self.holder);
}
}
fn main() {
let account = Rc::new(RefCell::new(Account { balance: 100 }));
let ana = Card {
holder: "Ana",
account: Rc::clone(&account),
};
let ben = Card {
holder: "Ben",
account: Rc::clone(&account),
};
ana.spend(30);
ben.spend(25);
account.borrow_mut().balance += 50;
println!("deposit 50");
println!("balance: {}", account.borrow().balance);
println!("owners: {}", Rc::strong_count(&account));
}
It prints:
Ana spends 30
Ben spends 25
deposit 50
balance: 95
owners: 3
Both cards and main own the same account: 100 – 30 – 25 + 50 = 95. spend takes &self, not &mut self, and still changes the balance. Each borrow_mut() lasts for one statement, so the borrows never overlap.
Cell: for small Copy values
For a value that’s Copy, like a counter, Cell<T> is simpler. It never hands out a reference to the inside. You get a copy out and set a new value in, so there’s nothing to borrow and nothing that can panic:
use std::cell::Cell;
struct Counter {
name: &'static str,
visits: Cell<u32>,
}
impl Counter {
fn visit(&self) {
self.visits.set(self.visits.get() + 1);
}
}
fn main() {
let page = Counter {
name: "home",
visits: Cell::new(0),
};
page.visit();
page.visit();
page.visit();
println!("{} was visited {} times", page.name, page.visits.get());
}
It prints:
home was visited 3 times
Use Cell for numbers and flags, and RefCell for anything you need to borrow, like a Vec or a String.
Cycles: when the count never reaches 0
Rc frees a value when its count reaches 0. So what if two values own each other? Here, node a points at b, and b points back at a:
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
name: &'static str,
next: RefCell<Option<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn main() {
let a = Rc::new(Node {
name: "a",
next: RefCell::new(None),
});
let b = Rc::new(Node {
name: "b",
next: RefCell::new(None),
});
*a.next.borrow_mut() = Some(Rc::clone(&b));
*b.next.borrow_mut() = Some(Rc::clone(&a));
println!("a: strong = {}", Rc::strong_count(&a));
println!("b: strong = {}", Rc::strong_count(&b));
let weak_a = Rc::downgrade(&a);
drop(a);
drop(b);
println!("a and b are gone from main");
println!("a's node still has strong = {}", weak_a.strong_count());
println!("end of main");
}
It prints:
a: strong = 2
b: strong = 2
a and b are gone from main
a's node still has strong = 1
end of main
No drop a, no drop b. Not even after main ends. Each node has two owners: a variable in main, and the other node. When main lets go, each count falls to 1, and the only thing holding it there is the other node. Neither can go first, so neither ever goes. The memory is leaked: still allocated, and nothing can reach it to free it. (weak_a is a peek we’ll explain in a moment. It doesn’t own anything.)
Two nodes that own each other through Rc. When main drops a and b, each count falls from 2 to 1 and stops there.
Rust’s safety promise covers memory that’s freed too early or twice. It doesn’t promise that memory is always freed. A cycle of Rcs is safe Rust, and it leaks. In a program that runs for a few seconds, that may not matter. In a server that builds cycles on every request, memory grows until something gives.
Weak: a pointer that doesn’t own
The fix is to make one direction of the cycle not count. Weak<T> is a pointer to an Rc allocation that doesn’t add to the strong count:
Rc::downgrade(&rc)makes aWeakand adds 1 to the weak count instead;weak.upgrade()returnsOption<Rc<T>>:Someif the value is still alive,Noneif it’s been dropped;Rc::weak_count(&rc)reads the weak count.
A Weak never keeps the value alive, so you have to ask, every time, whether it’s still there. Here a owns b with an Rc, and b points back at a with a Weak:
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
name: &'static str,
next: RefCell<Option<Rc<Node>>>,
back: RefCell<Weak<Node>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn look_back(node: &Node) {
match node.back.borrow().upgrade() {
Some(other) => println!("{} looks back and finds {}", node.name, other.name),
None => println!("{} looks back and finds nothing", node.name),
}
}
fn main() {
let a = Rc::new(Node {
name: "a",
next: RefCell::new(None),
back: RefCell::new(Weak::new()),
});
let b = Rc::new(Node {
name: "b",
next: RefCell::new(None),
back: RefCell::new(Weak::new()),
});
*a.next.borrow_mut() = Some(Rc::clone(&b));
*b.back.borrow_mut() = Rc::downgrade(&a);
println!(
"a: strong = {}, weak = {}",
Rc::strong_count(&a),
Rc::weak_count(&a)
);
println!(
"b: strong = {}, weak = {}",
Rc::strong_count(&b),
Rc::weak_count(&b)
);
look_back(&b);
drop(a);
println!("main dropped a");
look_back(&b);
println!("end of main");
}
It prints:
a: strong = 1, weak = 1
b: strong = 2, weak = 0
b looks back and finds a
drop a
main dropped a
b looks back and finds nothing
end of main
drop b
Read the counts first. a has one owner, main, and one Weak looking at it from b. b has two owners: main and a.next.
When main drops a, the strong count goes from 1 to 0, so node a is dropped at once. Dropping it drops its next field, which lowers b‘s count to 1. Now upgrade() returns None, and b finds nothing. At the end of main, b goes too. Every drop line printed.
Weak::new() makes a Weak that points at nothing yet. Its upgrade() always returns None.
Deref: why a Box acts like what’s inside
You’ve seen Box and Rc behave like the value they hold: sum(rest) took a &Box<List> where a &List was wanted, and a.0 reached into a Book through an Rc. That comes from the Deref trait. A type that implements Deref tells Rust “follow me to a T“, and Rust does that for *, for method calls and when passing a reference:
use std::rc::Rc;
fn shout(text: &str) -> String {
text.to_uppercase()
}
fn main() {
let boxed = Box::new(String::from("ana"));
let shared = Rc::new(String::from("ben"));
println!("{} letters, {} letters", boxed.len(), shared.len());
println!("{} {}", shout(&boxed), shout(&shared));
let back_out: String = *boxed;
println!("moved out of the box: {back_out}");
println!("an Rc is {} bytes", std::mem::size_of::<Rc<String>>());
}
It prints:
3 letters, 3 letters
ANA BEN
moved out of the box: ana
an Rc is 8 bytes
&boxed is a &Box<String>. Rust follows it to &String, then to &str, which is what shout wants. *boxed moves the String out of the box, because the box is its only owner. You can’t do that with an Rc, since others may still be reading. RefCell doesn’t implement Deref, which is why you call borrow() by hand. Part 22 shows how to write Deref for your own types.
Worked example: a folder tree that knows its parent
A folder owns its children: delete the folder and the children go with it. A child also wants to know its parent, to print its full path. If the child owned its parent too, we’d have the cycle from above. So children are Rc (owned), and the parent is Weak (only looked at):
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Folder {
name: String,
parent: RefCell<Weak<Folder>>,
children: RefCell<Vec<Rc<Folder>>>,
}
impl Folder {
fn new(name: &str) -> Rc<Folder> {
Rc::new(Folder {
name: name.to_string(),
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
fn path(&self) -> String {
match self.parent.borrow().upgrade() {
Some(parent) => format!("{}/{}", parent.path(), self.name),
None => self.name.clone(),
}
}
}
impl Drop for Folder {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn add_child(parent: &Rc<Folder>, child: &Rc<Folder>) {
*child.parent.borrow_mut() = Rc::downgrade(parent);
parent.children.borrow_mut().push(Rc::clone(child));
}
fn main() {
let home = Folder::new("home");
let ana = Folder::new("ana");
let notes = Folder::new("notes");
add_child(&home, &ana);
add_child(&ana, ¬es);
println!("{}", notes.path());
println!(
"ana: strong = {}, weak = {}",
Rc::strong_count(&ana),
Rc::weak_count(&ana)
);
drop(ana);
println!("main let go of ana; notes still says {}", notes.path());
drop(home);
println!("main let go of home; notes now says {}", notes.path());
}
It prints:
home/ana/notes
ana: strong = 2, weak = 1
main let go of ana; notes still says home/ana/notes
drop home
drop ana
main let go of home; notes now says notes
drop notes
Walk through it:
anahas strong count 2:mainandhome‘s list of children. Its weak count is 1:noteslooking up at it.- When
maindropsana, nothing is freed.homestill owns it, sonotescan still find its whole path. - When
maindropshome, its count hits 0. Droppinghomedrops its children list, which was the last owner ofana, soanagoes too.notessurvives, becausemainstill owns it. Itsupgrade()now returnsNone, so its path is justnotes.
The rule of thumb for trees and graphs: owners point down, Weak points up. Parents own children. Children only look at parents.
Worked example: a RefCell panic far from the bug
A RefCell panic tells you where the second borrow happened. The first borrow, the one that’s really in the way, can be somewhere else. Here a playlist can add a song, and can repeat every song it has:
use std::cell::RefCell;
struct Playlist {
songs: RefCell<Vec<String>>,
}
impl Playlist {
fn add(&self, song: &str) {
self.songs.borrow_mut().push(song.to_string());
}
fn repeat_all(&self) {
for song in self.songs.borrow().iter() {
self.add(song);
}
}
}
fn main() {
let list = Playlist {
songs: RefCell::new(Vec::new()),
};
list.add("Intro");
list.add("Outro");
list.repeat_all();
println!("{:?}", list.songs.borrow());
}
It prints:
panicked at src/main.rs:9:20:
RefCell already borrowed
Line 9 is inside add, and add looks fine. It borrows, pushes, and lets go. The problem is the caller. In repeat_all, the for loop holds self.songs.borrow() for the whole loop, and each turn calls add, which asks for borrow_mut() on the same RefCell. A reader and a writer at once: the rule from Part 7, caught at run time.
Without RefCell, this is the “can’t push while holding a reference” error from Part 8, and the compiler would have caught it. With RefCell, you find it when the code runs. The fix is the same as in Part 8: finish reading before you start writing. Here, copy the list first, so the borrow ends before the loop:
use std::cell::RefCell;
struct Playlist {
songs: RefCell<Vec<String>>,
}
impl Playlist {
fn add(&self, song: &str) {
self.songs.borrow_mut().push(song.to_string());
}
fn repeat_all(&self) {
let copy = self.songs.borrow().clone();
for song in © {
self.add(song);
}
}
}
fn main() {
let list = Playlist {
songs: RefCell::new(Vec::new()),
};
list.add("Intro");
list.add("Outro");
list.repeat_all();
println!("{:?}", list.songs.borrow());
}
It prints:
["Intro", "Outro", "Intro", "Outro"]
self.songs.borrow().clone() borrows, clones and drops the guard, all in one statement. By the time the loop calls add, nobody’s reading.
Tips and traps
- Reaching for
Rc<RefCell<T>>first. It compiles where plain references don’t, so it’s tempting. But it moves borrow errors from compile time to run time, where they’re panics. Try plain ownership and&/&mutfirst. UseRc<RefCell<T>>when there truly are several owners that change the data. - “RefCell already borrowed” (or “already mutably borrowed”). Two borrows overlap, and one of them is
borrow_mut. The panic points at the second one. Look for a guard that’s still alive: alet r = x.borrow();higher up, or aforloop overx.borrow(). Make the first borrow end sooner, or usetry_borrow_mutto check. - A
Dropthat never prints. If a value’sdropnever runs, look for a cycle ofRcs. PrintRc::strong_count. A count stuck above 0 after every variable is gone means something else owns it. Make the back pointer aWeak. Rc::cloneis cheap;.clone()on what’s inside isn’t.Rc::clone(&a)adds 1 to a counter.(*a).clone()copies the whole value. WriteRc::clone(&a)so the difference is visible.Rcacross threads. Moving anRcintothread::spawnfails with E0277, “Rc<i32>cannot be sent between threads safely”. The counter isn’t thread-safe. UseArcandMutex, from Part 24.upgrade()can fail. AWeakdoesn’t keep anything alive. Always handle theNonecase. Don’tunwrap()it unless you can say why the owner is still alive.
Boxowns alone,Rcshares and counts,RefCellchecks borrows at run time, andWeaklooks without owning.
Exercises
Exercise 1. This binary tree doesn’t compile. Fix it with Box, then add a method sum(&self) -> i32 that adds up every value in the tree. Build a tree with the values 1, 2, 3 and 4 and print its sum.
struct Tree {
value: i32,
left: Option<Tree>,
right: Option<Tree>,
}
fn main() {
let leaf = Tree {
value: 2,
left: None,
right: None,
};
let root = Tree {
value: 1,
left: Some(leaf),
right: None,
};
println!("root holds {}", root.value);
}
It prints:
error[E0072]: recursive type `Tree` has infinite size
Exercise 2. Without running it, write down the four numbers this prints, and whether the last line says true or false:
let a = Rc::new(5);
let b = Rc::clone(&a);
let w = Rc::downgrade(&a);
{
let c = Rc::clone(&b);
println!("{}", Rc::strong_count(&c));
}
drop(a);
println!("{} {}", Rc::strong_count(&b), Rc::weak_count(&b));
drop(b);
println!("{} {}", w.strong_count(), w.upgrade().is_some());
Exercise 3. A logger is shared by several parts of a program, so log must take &self, not &mut self. Make this compile without changing the signature of log, so it prints 2 lines.
struct Logger {
lines: Vec<String>,
}
impl Logger {
fn log(&self, line: &str) {
self.lines.push(line.to_string());
}
}
fn main() {
let logger = Logger { lines: Vec::new() };
logger.log("start");
logger.log("stop");
println!("{} lines", logger.lines.len());
}
It prints:
error[E0596]: cannot borrow `self.lines` as mutable, as it is behind a `&` reference
Answers
1. Wrap each child in a Box, so a Tree holds two pointers instead of two trees. as_ref() turns an &Option<Box<Tree>> into an Option<&Box<Tree>>, and map_or(0, ...) gives 0 for a missing child:
struct Tree {
value: i32,
left: Option<Box<Tree>>,
right: Option<Box<Tree>>,
}
impl Tree {
fn leaf(value: i32) -> Tree {
Tree {
value,
left: None,
right: None,
}
}
fn sum(&self) -> i32 {
let left = self.left.as_ref().map_or(0, |t| t.sum());
let right = self.right.as_ref().map_or(0, |t| t.sum());
self.value + left + right
}
}
fn main() {
let root = Tree {
value: 1,
left: Some(Box::new(Tree::leaf(2))),
right: Some(Box::new(Tree {
value: 3,
left: Some(Box::new(Tree::leaf(4))),
right: None,
})),
};
println!("sum = {}", root.sum());
}
It prints:
sum = 10
2. a, b and c make 3 owners. When the block ends, c goes, and dropping a leaves only b: strong 1, with one Weak. When b goes, the count is 0, the value is dropped, and upgrade() returns None:
use std::rc::Rc;
fn main() {
let a = Rc::new(5);
let b = Rc::clone(&a);
let w = Rc::downgrade(&a);
{
let c = Rc::clone(&b);
println!("{}", Rc::strong_count(&c));
}
drop(a);
println!("{} {}", Rc::strong_count(&b), Rc::weak_count(&b));
drop(b);
println!("{} {}", w.strong_count(), w.upgrade().is_some());
}
It prints:
3
1 1
0 false
3. Put the Vec inside a RefCell, and call borrow_mut() to push and borrow() to read:
use std::cell::RefCell;
struct Logger {
lines: RefCell<Vec<String>>,
}
impl Logger {
fn log(&self, line: &str) {
self.lines.borrow_mut().push(line.to_string());
}
}
fn main() {
let logger = Logger {
lines: RefCell::new(Vec::new()),
};
logger.log("start");
logger.log("stop");
println!("{} lines", logger.lines.borrow().len());
}
It prints:
2 lines
To share the logger between several owners, wrap it once more: Rc<Logger>. Each owner holds an Rc::clone, and every one of them can call log.
What’s next
Box<dyn Error> came up in Part 12 and again in this part: a box holding “some type that implements a trait”. In Part 21, we’ll open up those trait objects: what dyn means, the table of functions a dyn pointer carries, and when to choose them over generics.