Rust

Rc and Arc — Shared Ownership

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Rc<T>` lets multiple owners share read-only access in single-threaded code; `Arc<T>` is the thread-safe version. Pair with `RefCell` / `Mutex` when you need shared MUTABLE access.
Rust
Raw
use std::rc::Rc;
use std::sync::Arc;

fn main() {
    // Single-threaded shared ownership
    let shared = Rc::new(vec![1, 2, 3]);
    let a = Rc::clone(&shared);          // bumps refcount, no deep copy
    let b = Rc::clone(&shared);
    println!("count={}", Rc::strong_count(&shared)); // 3
    println!("{a:?} {b:?}");
    // When the last Rc is dropped, the Vec is freed.

    // Multi-threaded — Arc is atomic refcounted
    let big = Arc::new(vec![0u8; 1024 * 1024]);
    let handles: Vec<_> = (0..4).map(|i| {
        let chunk = Arc::clone(&big);
        std::thread::spawn(move || chunk.iter().take(10 + i).count())
    }).collect();
    for h in handles { println!("counted {}", h.join().unwrap()); }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.