Interior Mutability: RefCell, Cell
Learn about `RefCell` and `Cell` for interior mutability, allowing mutable access to data through an immutable reference, safely.
What is Interior Mutability?
In Rust, the borrowing rules usually prevent you from having a mutable reference to data if you already have an immutable reference to it. This ensures data safety.
Interior mutability is a design pattern that allows you to mutate data even when you only have an immutable reference to it. It's like a controlled exception to Rust's usual rules, used in specific situations.
`Cell<T>`: For Copy Types
The Cell<T> type provides interior mutability for types that implement the Copy trait (like integers, booleans, characters). It works by replacing the value inside.
get(): Returns a copy of the value inside theCell.set(value): Replaces the value inside theCellwith a new one.
It's simple and efficient for small, copyable data.
All lessons in this course
- Box, Rc, and Arc Smart Pointers
- Interior Mutability: RefCell, Cell
- Fearless Concurrency with Threads