Rust
December 2, 2026 8 min read

Smart Pointers in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Are Smart Pointers?

A pointer is a variable that stores the memory address of another value.

A smart pointer is a data structure that behaves like a pointer but also provides additional functionality.

Rust uses smart pointers to manage memory and ownership.

Regular Variable

fn main() {
let number = 100;

println!("{}", number);
}

Smart Pointer Example

fn main() {
let number = Box::new(100);

println!("{}", number);
}

Output:

100

Here, Box::new(100) stores the integer value on the heap.

2. Understanding Stack and Heap Memory

Rust uses two important memory areas:

Stack

The stack stores values with a known, fixed size and manages them using a last-in, first-out structure.

Heap

The heap stores data that is allocated dynamically.

For example:

fn main() {
let number = 100;

let heap_number = Box::new(200);

println!("Stack: {}", number);
println!("Heap: {}", heap_number);
}

Output:

Stack: 100
Heap: 200

In this example:

  1. number is an integer stored directly in the stack frame.
  2. heap_number is a Box pointer stored in the stack frame, while its integer value is stored on the heap.

3. Box<T> – Heap Allocation

Box<T> is used to store a value on the heap.

It provides ownership of the heap-allocated value.

Syntax:

let variable = Box::new(value);

Example:

fn main() {
let number = Box::new(500);

println!("Number: {}", number);
}

Output:

Number: 500

Accessing Box Values

You can access the value using dereferencing.

fn main() {
let number = Box::new(100);

println!("{}", *number);
}

Output:

100

The * operator dereferences the Box.

Rust also automatically dereferences many smart pointers when accessing methods or formatting values.

Updating a Box Value

fn main() {
let mut number = Box::new(100);

*number = 200;

println!("{}", number);
}

Output:

200

When Should You Use Box<T>?

Use Box<T> when:

  1. You want to store data on the heap.
  2. You have a large value that you want to move without copying its entire contents.
  3. You need a recursive data structure.
  4. You need a value with a fixed-size pointer representation.

4. Rc<T> – Reference Counting

Rc<T> stands for Reference Counted.

It allows multiple parts of a program to share ownership of the same data.

Normally, Rust allows only one owner of a value.

However, sometimes multiple owners are useful.

Example:

use std::rc::Rc;

fn main() {
let number = Rc::new(100);

let a = Rc::clone(&number);
let b = Rc::clone(&number);

println!("Number: {}", number);
println!("A: {}", a);
println!("B: {}", b);
}

Output:

Number: 100
A: 100
B: 100

Here:

  1. number is the original owner.
  2. a shares ownership.
  3. b shares ownership.

All three refer to the same value.

Understanding Rc::clone()

let a = Rc::clone(&number);

This does not clone the underlying value.

Instead, it creates another reference-counted pointer and increases the reference count.

Checking the Reference Count

use std::rc::Rc;

fn main() {
let number = Rc::new(100);

println!("Count: {}", Rc::strong_count(&number));

let a = Rc::clone(&number);

println!("Count: {}", Rc::strong_count(&number));

let b = Rc::clone(&number);

println!("Count: {}", Rc::strong_count(&number));
}

Output:

Count: 1
Count: 2
Count: 3

Important: Rc Is Not Thread-Safe

Rc<T> is designed for sharing data within a single thread.

It should not be used to share ownership between threads.

For thread-safe shared ownership, Rust provides Arc<T>.

5. Arc<T> – Atomic Reference Counting

Arc<T> stands for Atomic Reference Counted.

It provides shared ownership like Rc<T>, but its reference counting is thread-safe.

Syntax:

use std::sync::Arc;

Example:

use std::sync::Arc;
use std::thread;

fn main() {
let number = Arc::new(100);

let a = Arc::clone(&number);

let handle = thread::spawn(move || {
println!("Thread value: {}", a);
});

println!("Main value: {}", number);

handle.join().unwrap();
}

Output:

Main value: 100
Thread value: 100

Explanation:

  1. Arc::new(100) creates shared ownership.
  2. Arc::clone() creates another shared pointer.
  3. thread::spawn() starts a new thread.
  4. move transfers the cloned Arc pointer into the thread.
  5. join() waits for the thread to finish.

Difference Between Rc and Arc


Feature

Rc<T>

Arc<T>

Full form

Reference Counted

Atomic Reference Counted

Shared ownership

Yes

Yes

Thread-safe reference counting

No

Yes

Common use

Single-threaded programs

Multi-threaded programs

Performance

Lower overhead

Higher overhead

6. RefCell<T> – Interior Mutability

Normally, Rust follows an important borrowing rule:

  1. You can have multiple immutable references.
  2. Or you can have one mutable reference.
  3. You cannot have both at the same time.

RefCell<T> allows mutation through an immutable reference to the RefCell itself.

It checks borrowing rules at runtime instead of compile time.

Example:

use std::cell::RefCell;

fn main() {
let number = RefCell::new(100);

*number.borrow_mut() = 200;

println!("{}", number.borrow());
}

Output:

200

Explanation:

  1. RefCell::new(100) creates a RefCell.
  2. borrow() creates an immutable runtime borrow.
  3. borrow_mut() creates a mutable runtime borrow.
  4. * allows us to modify the stored value.

Another Example

use std::cell::RefCell;

fn main() {
let name = RefCell::new(String::from("Hemant"));

name.borrow_mut().push_str(" Singh");

println!("{}", name.borrow());
}

Output:

Hemant Singh

Important: Runtime Borrowing Rules

RefCell<T> does not remove Rust's borrowing rules.

It checks them at runtime.

If you try to create conflicting borrows, the program panics.

Example:

use std::cell::RefCell;

fn main() {
let number = RefCell::new(100);

let first = number.borrow_mut();

let second = number.borrow_mut();

println!("{} {}", first, second);
}

This program panics because it attempts to create two simultaneous mutable borrows.

7. Combining Rc<T> and RefCell<T>

Sometimes we need both:

  1. Multiple owners.
  2. The ability to modify shared data.

We can combine Rc<T> and RefCell<T>.

Example:

use std::rc::Rc;
use std::cell::RefCell;

fn main() {
let number = Rc::new(RefCell::new(100));

let a = Rc::clone(&number);
let b = Rc::clone(&number);

*a.borrow_mut() = 200;

println!("A: {}", a.borrow());
println!("B: {}", b.borrow());
}

Output:

A: 200
B: 200

Both a and b share ownership of the same RefCell.

Changing the value through one owner is visible through the other.

Common use cases:

  1. Shared application state.
  2. Graph data structures.
  3. Tree structures.
  4. Single-threaded applications with shared mutable data.

8. Mutex<T> – Safe Shared Mutation Between Threads

Mutex<T> stands for Mutual Exclusion.

It allows multiple threads to access shared data safely, but only one thread can hold its lock at a time.

Example:

use std::sync::Mutex;

fn main() {
let number = Mutex::new(100);

{
let mut value = number.lock().unwrap();

*value = 200;
}

println!("{:?}", number);
}

Output:

Mutex { data: 200, ... }

Explanation:

  1. Mutex::new(100) creates a mutex.
  2. lock() requests exclusive access.
  3. unwrap() handles a possible lock error.
  4. *value = 200 modifies the stored value.
  5. When the guard goes out of scope, the lock is released.

Sharing Mutex Between Threads

A common pattern is combining Arc<T> and Mutex<T>.

Example:

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
let counter = Arc::new(Mutex::new(0));

let mut handles = vec![];

for _ in 0..3 {
let counter = Arc::clone(&counter);

let handle = thread::spawn(move || {
let mut value = counter.lock().unwrap();

*value += 1;
});

handles.push(handle);
}

for handle in handles {
handle.join().unwrap();
}

println!("Counter: {}", *counter.lock().unwrap());
}

Output:

Counter: 3

Explanation:

  1. Arc allows multiple threads to share ownership.
  2. Mutex protects the shared counter.
  3. Each thread locks the counter before modifying it.
  4. Each thread increases the value by one.
  5. join() waits for every thread to finish.

The final value is 3.

9. Difference Between Box, Rc, Arc, RefCell, and Mutex


Smart Pointer

Main Purpose

Box<T>

Stores an owned value on the heap

Rc<T>

Shared ownership in one thread

Arc<T>

Shared ownership across threads

RefCell<T>

Runtime-checked interior mutability

Mutex<T>

Exclusive access to shared data using a lock

10. Understanding Deref and Drop Traits

Smart pointers often implement special Rust traits.

Deref Trait

The Deref trait allows a smart pointer to behave like a reference to its stored value.

Example:

fn main() {
let name = Box::new(String::from("Rust"));

println!("Length: {}", name.len());
}

Here, Rust automatically dereferences the Box when calling len().

Drop Trait

The Drop trait allows a type to define what happens when its value goes out of scope.

Example:

struct Student;

impl Drop for Student {
fn drop(&mut self) {
println!("Student object destroyed");
}
}

fn main() {
let student = Student;

println!("Program running");
}

Output:

Program running
Student object destroyed

Rust automatically calls the drop() method when the value goes out of scope.

11. When Should You Use Each Smart Pointer?


Situation

Recommended Type

Heap allocation

Box<T>

Multiple owners in one thread

Rc<T>

Multiple owners across threads

Arc<T>

Single-threaded shared mutation

Rc<RefCell<T>>

Shared mutation across threads

Arc<Mutex<T>>

Choose the simplest ownership model that solves your problem. Smart pointers are useful, but you do not need them for every variable.

12. Common Mistakes


Mistake

Explanation

Using Rc across threads

Rc is not thread-safe

Using borrow_mut() while a conflicting borrow exists

Causes a runtime panic

Forgetting to lock a Mutex

You cannot directly mutate its protected value

Confusing Box and Rc

Box provides single ownership; Rc provides shared ownership

Assuming Arc makes all data thread-safe

Arc makes reference counting thread-safe, not arbitrary inner data

Holding a Mutex lock too long

Can block other threads and contribute to deadlocks