Skip to content

Chapter 8 of 8

Smart Pointers and Unsafe Rust

Beyond plain references, Rust offers smart pointers that own or manage data in more sophisticated ways. `Box` allocates a value on the heap and owns the only pointer to it. It is essential for recursive types whose size cannot be known at compile time, for transferring ownership of large data without copying it, and for trait objects written as `Box`.

For shared ownership within a single thread, `Rc` keeps a non-atomic reference count, while `Arc` is its thread-safe counterpart with an atomic counter. The rule of thumb is to use `Arc` whenever the data crosses a thread boundary and `Rc` otherwise, because the atomic operations in `Arc` carry a small performance cost that is wasted in purely sequential code.

For the rare situations where the compiler's safety guarantees are too restrictive, Rust provides the `unsafe` keyword. Inside an `unsafe` block you may dereference raw pointers, call unsafe functions, access or modify mutable statics, implement unsafe traits, and access union fields. Importantly, `unsafe` does not disable the borrow checker; it merely opens a small set of additional capabilities that the programmer must verify by hand and document carefully.

Raw pointers, written `*const T` and `*mut T`, are at the heart of unsafe code. They resemble C pointers: they can be null, dangling, or aliased without complaint from the compiler. Creating a raw pointer is safe, but dereferencing one requires `unsafe`. Used sparingly, with clear invariants and thorough documentation, unsafe code lets Rust interoperate with hardware, foreign functions, and performance-critical low-level patterns while keeping the vast majority of the codebase in safe Rust.

All chapters
  1. 1Foundations of Rust Memory Safety
  2. 2Structures, Enums, and Pattern Matching
  3. 3Error Handling with Option and Result
  4. 4Traits, Generics, and Polymorphism
  5. 5Iterators, Closures, and Functional Patterns
  6. 6Modules, Crates, Cargo, and Testing
  7. 7Concurrency in Rust
  8. 8Smart Pointers and Unsafe Rust

Drill it

Reading is not remembering. These come from the Rust Programming deck:

Q

What is Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It achieves memory safety without a garbage collector through its ownership sy...

Q

What is ownership in Rust?

Ownership is Rust's core memory management concept. Each value has exactly one owner, and when the owner goes out of scope, the value is dropped (freed). This p...

Q

What are the three ownership rules in Rust?

Each value in Rust has a single ownerThere can only be one owner at a timeWhen the owner goes out of scope, the value is dropped

Q

What is borrowing in Rust?

Borrowing lets you reference a value without taking ownership. You create a reference with &. The original owner retains ownership while the borrower can re...