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)
Syntax
Box::new(v) Rc::new(v) / Rc::clone(&rc) RefCell::new(v).borrow_mut() Arc::new(Mutex::new(v))
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
#[derive]· Generate standard trait implementations such as Debug, Clone, PartialEq, Eq, Hash, Default and PartialOrd for your types.- Rust Smart Pointers: Box, Rc and RefCell · tutorial
- Rust Shared State: Arc and Mutex · tutorial