💠 Rust Cells
= a type to perform (non-thread-safe) interior mutability, part of std::cell
Types
Cell<T>
= a struct containing a private value of Type T, which can be get/set, even without ownership
Cell::new(val)→ new Cell, moving val into itcell.get()→ returns copy of valcell.set(new_val)→ storesnew_valincell- doesn’t take
&mutas parameter
- doesn’t take
Requirements
- T implements the copy trait
RefCell<T>
= like Cell T, but supports borrowing references to val of T
RefCell::new(val)→ new RefCell, move val into itref_cell.borrow()- → returns
Ref<T>(= shared reference to val in ref_cell) - panic if val is mutably borrowed
- → returns
ref_cell.borrow_mut()- → returns
RefMut<T>(mut reference to val in ref_cell) - panic if val is already borrowed
- → returns
ref_cell.try_borrow(),ref_cell.try_borrwo_mut()- → like
borrow(),borrow_mut(), but returns Result
- → like