πŸ”§
World 15 Β· Smart Pointers

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.

New word To borrow means to take a quick look without taking ownership. borrow() looks but doesn't change. borrow_mut() looks and changes.
Think of it like this… A money box looks sealed, but it has a little plug on the bottom. You can open the plug to add or take out coins, then close it again. RefCell is that plug! πŸ’°

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.

Watch out! RefCell checks the rules while running. If you try to change and read at the very same moment, it will stop the program to keep you safe. So borrow one at a time! ⏱️
Ferris says: RefCell trusts you a little more, but still has your back. Borrow politely and you'll be just fine. πŸ¦€
Try this! Change the += 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. πŸ”§

You learned… A 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! πŸš€