BorrowCheck › Rust language core

Smart pointers, interior mutability

Box, Rc / Arc, RefCell / Cell, Weak and cycles, Cow, the Deref trait.

The topic explains the standard library's smart pointers and interior mutability. The Box subtopic shows when a value is put on the heap: a recursive type without indirection (E0072), values of unknown size and trait objects, the size of Box itself and of Option<Box<T>>, and Box::leak. The questions on Rc and Arc check reference counting, the difference between cloning the pointer and cloning the value, comparison with == versus Rc::ptr_eq, getting the value back with Rc::try_unwrap, Rc::into_inner and Rc::make_mut, and why an Rc cannot be sent to another thread. The subtopics on Cell, RefCell and OnceCell cover mutation through &self and panics on conflicting borrows at run time, including a temporary borrow guard that lives until the end of a statement or a match expression; the Weak subtopic covers strong and weak counts and the reference cycles that cause leaks. The last subtopics are about Cow and clone-on-write (to_mut, into_owned) and about the Deref trait: why deref returns a reference, why DerefMut requires Deref, and when implementing Deref for one's own type is appropriate. The topic builds on ownership and borrowing and prepares for concurrency.

46 questions: 20 basic, 22 intermediate, 4 advanced. 6 info pages, 21 sources.

Subtopics

  1. Box<T>
  2. Rc and Arc
  3. RefCell, Cell, interior mutability
  4. Weak and reference cycles
  5. Cow<'a, T>
  6. The Deref trait

Previous: Modules, Cargo, features, editions · Next: Drop, RAII, drop order