Module lessons (2/2)
Smart Pointers: Box<T>, Rc<T> and RefCell<T>
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
- 11.
Box<T>: Explicit heap and recursive types - 22.
Rc<T>: Reference Counting single-thread - 33.
RefCell<T>: Internal mutability checked at runtime - 44. Combine
RcandRefCell - 5Practical exercises
- 6Check for understanding
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.