Skip to main content
Module 6 · Lesson 2 of 212/24 in the course~22 min
Module lessons (2/2)

Smart Pointers: Box<T>, Rc<T> and RefCell<T>

Lesson preview5 hands-on exercises readyCourse Rust · Module 6 — Lifetimes & Smart Pointers

Allocate recursive types in Heap with Box<T>, share ownership single-thread with Rc::clone, and internal mutability checked with RefCell<T>.

What you'll learn in this lesson

  • Use Box<T> to allocate data on the Heap and allow recursive types (lists, trees).
  • Share a read-only value between multiple single-threaded owners via Rc<T>.
  • Understanding the internal mutability pattern with RefCell<T> (dynamic control of Borrowing rules at runtime).

Overview

Unlike a normal reference (&T) which simply borrows a value, a Smart Pointer owns the data it points to by implementing the traits Deref (acts like a reference) and Drop (cleans resources when exiting scope).

A Box<T> stores the data on the Heap leaving only a fixed-size pointer on the Stack. It is indispensable when you define recursive structures (a node contains itself) whose size would otherwise be infinite!

Sections covered in this lesson

  1. 11. Box<T>: Explicit heap and recursive types
  2. 22. Rc<T>: Reference Counting single-thread
  3. 33. RefCell<T>: Internal mutability checked at runtime
  4. 44. Combine Rc and RefCell
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 6 — Lifetimes & Smart Pointers

Unlock "Smart Pointers: Box<T>, Rc<T> and RefCell<T>" and the full Course Rust curriculum

Allocate recursive types in Heap with `Box<T>`, share ownership single-thread with `Rc::clone`, and internal mutability checked with `RefCell<T>`.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.