Smart pointers

Box

  • for allocating values on the heap
let b = Box::new(5);

Rc

  • multiple ownership with reference counting
let a = Rc::new(5);
let b = Rc::clone(&a);

Ref, RefMut, and RefCell

  • enforce borrowing rules at runtime instead of compile time.
let num = 5;
let r1 = RefCell::new(5);
// Ref - immutable borrow
let r2 = r1.borrow();
// RefMut - mutable borrow
let r3 = r1.borrow_mut();
// RefMut - second mutable borrow
let r4 = r1.borrow_mut();

Multiple owners of mutable data

let x = Rc::new(RefCell::new(5));