πŸ‘₯
World 15 Β· Smart Pointers

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.

New word Reference counting means keeping a tally of how many sharers a value has. When the tally hits zero, the value is cleaned up. 🧹
Think of it like this… One library book, many readers, and a checkout card that counts. Each new reader adds +1 to the count. Nobody made a second copy of the book β€” they all share the same one!

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. πŸ“ˆ

Ferris says: Rc is for one thread at a time β€” like sharing within a single room, not across many rooms at once. πŸ¦€
Try this! Add one more line: 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. πŸ‘₯

You learned… 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! πŸ”§