Rust Smart Pointers — Box, Rc, RefCell, and Interior Mutability Patterns
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Smart Pointers. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust smart pointers include Box for heap allocation, Rc for reference counting, RefCell for interior mutability, and Cell for copy types.
What You'll Learn
- Box for heap allocation
- Rc for shared ownership
- RefCell for interior mutability
- Deref and Drop traits
Why It Matters
Smart pointers enable patterns not possible with basic ownership. DodaZIP uses Box for trait objects and Rc for shared configuration.
Real-World Use
Recursive data structures, graph structures, shared state, plugin trait objects.
use std::rc::Rc;
use std::cell::RefCell;
// Box for heap allocation
fn box_example() {
let b = Box::new(5);
println!("b = {}", b);
// Recursive type needs Box
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{:?}", list);
}
// Rc for shared ownership
fn rc_example() {
let a = Rc::new(5);
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Reference count: {}", Rc::strong_count(&a));
}
// RefCell for interior mutability
fn refcell_example() {
let value = Rc::new(RefCell::new(5));
let shared = Rc::clone(&value);
*value.borrow_mut() += 10;
println!("Value: {}", shared.borrow());
}
fn main() {
box_example();
rc_example();
refcell_example();
}
← Previous
Rust Closures and Iterators — Anonymous Functions, Capturing, and Iterator Adapters
Next →
Rust Strings — Understanding String, &str, and UTF-8 Text Handling
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro