Rust Reference ยท Smart Pointers and Memory
Rust RefCell<T> type
Reference for Rust RefCell<T>: borrow, borrow_mut, try_borrow, Ref and RefMut guards, BorrowMutError panics and the Rc<RefCell<T>> pattern.
RefCell<T> provides interior mutability with borrow rules checked while the program runs instead of at compile time. You call borrow() to get a shared guard (Ref<T>) or borrow_mut() to get an exclusive guard (RefMut<T>), both through a plain &RefCell<T>.
The rules are the same as for ordinary references: any number of shared borrows, or exactly one mutable borrow, never both. The cell counts active guards; breaking the rule makes borrow/borrow_mut panic, while try_borrow/try_borrow_mut return an Err instead. Like Cell, RefCell is not Sync.
use std::cell::RefCell; let list = RefCell::new(vec![1, 2]); list.borrow_mut().push(3);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub struct RefCell<T: ?Sized> { /* private */ } impl<T> RefCell<T> { pub const fn new(value: T) -> RefCell<T>; pub fn into_inner(self) -> T; pub fn replace(&self, t: T) -> T; pub fn swap(&self, other: &RefCell<T>); } impl<T: ?Sized> RefCell<T> { pub fn borrow(&self) -> Ref<'_, T>; pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError>; pub fn borrow_mut(&self) -> RefMut<'_, T>; pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError>; pub fn get_mut(&mut self) -> &mut T; }
| Method | Description |
|---|---|
borrow() |
Shared guard; panics if a mutable borrow is active. |
borrow_mut() |
Exclusive guard; panics if any other borrow is active. |
try_borrow() / try_borrow_mut() |
Same checks, returning Result instead of panicking. |
replace(v) / take() |
Swap in a new value (or Default) and return the old one; panics if borrowed. |
get_mut() |
Plain &mut T when you hold &mut RefCell<T>: no run-time check. |
Errors / panics. borrow_mut panics with RefCell already borrowed (or already mutably borrowed for borrow). The guards Ref and RefMut release the borrow when dropped, and Ref::map / RefMut::map narrow a guard to a field.
Usage notes
- The classic combination is
Rc<RefCell<T>>: shared ownership plus mutation. Keep eachborrow_mut()guard short-lived; a guard stored in a variable lives until the end of its scope. - Temporaries live to the end of the statement:
if cell.borrow().is_empty() { cell.borrow_mut().push(1) }is fine, because the temporaries of anifcondition drop before the block runs. Be careful withmatch cell.borrow().x { ... }, where the guard lasts through the whole match. - Re-entrancy is the usual source of panics: a callback invoked while a guard is held that touches the same cell.
RefCellcosts one integer of bookkeeping and a check per borrow. If you only need aCopyflag, useCell.- Across threads use
MutexorRwLock; they block instead of panicking. - Prefer designs that need no
RefCell(indices into aVec, passing&mutexplicitly). It is a tool for graphs, observers and mock objects, not a way around every borrow error.
Related
- Cell, Rc, OnceCell and LazyCell
- Tutorial: RefCell and Cell, Rc and Arc, Mutex and RwLock