Smart Pointers
Heap allocation and shared ownership with smart pointers. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Heap allocation and shared ownership with smart pointers. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Own a heap-allocated value; enables recursive types.
let b = Box::new(5);
*b // 5Single-threaded reference counting.
use std::rc::Rc;
let a = Rc::new(1);
let b = Rc::clone(&a);
Rc::strong_count(&a) // 2Interior mutability checked at runtime.
use std::cell::RefCell;
let c = RefCell::new(1);
*c.borrow_mut() += 1;
*c.borrow() // 2Thread-safe shared mutability pair.
use std::sync::{Arc, Mutex};
let m = Arc::new(Mutex::new(1));
*m.lock().unwrap() += 1;
*m.lock().unwrap() // 2Borrow until mutation requires ownership.
use std::borrow::Cow;
fn add_hi(s: Cow<str>) -> Cow<str> {
if s.contains("hi") { s } else { format!("{s} hi").into() }
}
add_hi("x".into()) // "x hi"Leak to get &'static - rare, intentional.
let s: &'static str = Box::leak(String::from("x").into_boxed_str());
s // "x"Break Rc cycles with Weak.
use std::rc::{Rc, Weak};
let strong = Rc::new(1);
let w: Weak<_> = Rc::downgrade(&strong);
w.upgrade().map(|r| *r) // Some(1)Pin guarantees an object will not move - required for some self-referential futures.
// use std::pin::Pin;
// Pin<&mut T> after ensuring immovableBox derefs to T.
fn f(n: &i32) -> i32 { *n }
f(&Box::new(3)) // 3Cell for Copy types without RefCell borrow flags.
use std::cell::Cell;
let c = Cell::new(1);
c.set(2);
c.get() // 2Shared ownership + mutation for graphs/trees.
use std::rc::Rc;
use std::cell::RefCell;
let n = Rc::new(RefCell::new(0));
*n.borrow_mut() = 5;
*n.borrow() // 5Type-erase errors as trait objects.
fn go() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
go().is_ok() // truePrevent Drop - unsafe territory for niche cases.
use std::mem::ManuallyDrop;
let m = ManuallyDrop::new(String::from("x"));
// must not double-free if you take innerPrefer Box over raw pointers for single ownership heaps.
struct Node { v: i32, next: Option<Box<Node>> }
let n = Node { v: 1, next: None };
n.v // 1Cloning Arc bumps the count - O(1).
use std::sync::Arc;
let a = Arc::new(vec![1, 2]);
let b = a.clone();
b.len() // 2Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Reviewed by Chris St. John·Last updated Jul 18, 2026