RefCell: Bending Rules Safely
Some gadgets look sealed up tight, but they have a clever little hatch you can open to swap the batteries inside. In Rust, a RefCell is that hatch β it lets you change something that otherwise looks fixed, while still keeping you safe. π§
Changing the βunchangeableβ
Normally Rust is strict about who can change a value. A RefCell<T> lets you peek
inside and change the value, even when the RefCell itself looks fixed. It still
keeps you safe, but it does its safety check while the program runs instead of
before.
borrow() looks but doesn't change. borrow_mut() looks
and changes.
Using borrow_mut
We open the hatch with borrow_mut() and change whatβs inside. Then we use
borrow() to read it again.
The little * is how we reach the value through the hatch to change it. We added
3 coins, and the money box went from 5 to 8. π
A great team: Rc plus RefCell
Remember Rc from last lesson? It shares but canβt change. RefCell changes but
isnβt shared. Put them together as Rc<RefCell<T>> and you get something that is
both shared and changeable β like a group scoreboard everyone can see and
update.
RefCell trusts you a little more, but
still has your back. Borrow politely and you'll be just fine. π¦
+= 3 to -= 2 and press βΆ Run.
What does the money box say now? π°
Quick quiz
What does borrow_mut() let you do?
Exactly! borrow_mut() opens the hatch so you can both read and change what's inside. π§
RefCell<T> lets you change data safely with
borrow_mut(), checking the rules as it runs. Paired as
Rc<RefCell<T>>, data can be shared and
changed. You've finished the Smart Pointers world β amazing work! Next up:
a whole new adventure awaits! π