Rust 1.99 (2024 edition) reference · Traits and Smart Pointers

Rust Box, Rc, RefCell and Arc Type

Choose the right smart pointer: heap allocation, shared ownership, interior mutability, and thread-safe sharing.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

Box::new(v)   Rc::new(v) / Rc::clone(&rc)   RefCell::new(v).borrow_mut()   Arc::new(Mutex::new(v))

Parameters

ParameterDescription
Box<T> Heap value, recursive types, trait objects.
Rc<T> / Arc<T> Shared ownership: single thread / across threads.
RefCell<T> Mutation checked at runtime (single thread).
Mutex<T> / RwLock<T> Mutation across threads.

Examples

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

fn main() {
    let shared = Rc::new(RefCell::new(Vec::new()));
    let writer = Rc::clone(&shared);
    writer.borrow_mut().push("event 1");
    shared.borrow_mut().push("event 2");
    println!("{:?}, owners: {}", shared.borrow(), Rc::strong_count(&shared));
}

Output

["event 1", "event 2"], owners: 2

Run this on your computer — see “Get Started” for setup.

Arc and Mutex across threads
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let handles: Vec<_> = (0..4).map(|_| {
        let c = Arc::clone(&counter);
        thread::spawn(move || *c.lock().unwrap() += 10)
    }).collect();
    for h in handles { h.join().unwrap(); }
    println!("{}", counter.lock().unwrap());
}

Output

40

Run this on your computer — see “Get Started” for setup.

Was this page helpful?