Rc: Sharing Ownership
Picture one really good library book that lots of people want to read. The library keeps a little card that counts how many readers have it checked out. When everyone returns it, the count goes back to zero. In Rust, Rc is that counting card! π₯
One thing, many owners
Usually in Rust, a value has just one owner. But sometimes lots of parts of
your program need to share the same thing. Rc<T> lets several owners share
one value. The Rc part stands for βreference countingβ β it keeps count of how
many owners there are.
Sharing with Rc::clone
To share, you call Rc::clone(...). This does not copy the whole value β it
just adds one to the count. You can peek at the count with Rc::strong_count.
See the count climb from 1 to 3 as more readers share the book? Each
Rc::clone says βI want to share too!β and bumps the number up. π
Rc is for one thread at a time β like
sharing within a single room, not across many rooms at once. π¦
let reader4 = Rc::clone(&book); and then print
the count again. What number do you expect? Press βΆ Run to check!
Quick quiz
What does Rc::clone do?
Right! Rc::clone shares the same value and increases the owner count by one. No copying needed. π₯
Rc<T> lets many owners share one value, counting
sharers with Rc::strong_count and adding them with
Rc::clone. But sharing alone can't change the value. What if
we want to bend that rule safely? Next up: RefCell: Bending Rules
Safely! π§