๐Ÿ’  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 it
  • cell.get() โ†’ returns copy of val
  • cell.set(new_val) โ†’ stores new_val in cell
    • doesnโ€™t take &mut as parameter
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 it
  • ref_cell.borrow()
    • โ†’ returns Ref<T> (= shared reference to val in ref_cell)
    • panic if val is mutably borrowed
  • ref_cell.borrow_mut()
    • โ†’ returns RefMut<T> (mut reference to val in ref_cell)
    • panic if val is already borrowed
  • ref_cell.try_borrow(), ref_cell.try_borrwo_mut()
    • โ†’ like borrow(), borrow_mut(), but returns Result