liveBook · Manning

Smart pointer

As explained in Learn Rust in a Month of Lunches

A smart pointer is a pointer-like data structure that manages an owned or referenced value and provides behavior beyond raw address storage.

A smart pointer is a pointer-like data structure that manages access to a value and provides behavior beyond storing a raw address. It can own data, carry metadata, expose methods, or support dereferencing with *. section 13.2.1 section 15.3.1

In Rust, smart pointers help with several practical problems:

  • Use Box to place owned data on the heap while keeping a known-size pointer. section 13.3
  • Use Box to give recursive structures a finite size, such as a Holder containing another Holder. section 13.2.1
  • Use Box<dyn trait> to treat a concrete value as a trait object and use its trait methods. section 13.3
  • Implement Deref when a custom wrapper should support dereferencing and behave more like the value it contains. section 15.3.1

Breaking a recursive type's infinite size

A direct recursive field such as Option<Holder> cannot compile because the compiler cannot determine the type's size. Wrapping the field as Option<Box<Holder>> adds indirection with a known size. Box::new then constructs each nested Holder, and *my_box accesses a boxed value just as dereferencing accesses a reference. section 13.2.1 section 13.3

Common smart pointers include Box, Rc, and RefCell; familiar types such as String and Vec also behave as smart pointers. The important idea is that the pointer supplies an interface or capability in addition to referring to data. section 15.3.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines smart pointers and works through Box and Deref, but does not develop Rc or RefCell behavior in detail.
Examples
Uses Box<i32>, recursive Holder values, compiler diagnostics, Box<dyn Error>, and a custom HoldsANumber wrapper.
What it assumes
Assumes basic references, dereferencing, structs, ownership, and traits while reinforcing references and compiler feedback through examples.
What you can do after
Apply it via Box and Deref to build recursive values, access boxed data, and design pointer-like wrappers.
How it connects
Connects smart pointers with ownership, heap allocation, recursion, dereferencing, trait objects, static dispatch, and dynamic dispatch.

Also explained in

Compare how 5 books explain smart pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.