FAQ - Help and questions

When do I use Box, Rc, Arc and Mutex in Rust?

#smart-pointers#ownership#concurrencypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Box puts one value on the heap with a single owner. Rc lets several owners in one thread share a value by counting them. Arc does the same across threads. To change a shared value, wrap it in a Mutex (or RefCell for single-thread Rc). Start with plain values and references, and reach for these only when needed.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Most Rust code needs none of these: values live in variables and are lent with &. They solve specific problems:

TypeOwnersThreadsUse it for
Box<T>oneanya value on the heap; recursive types; Box<dyn Trait>
Rc<T>manyone onlyshared read-only data in a single-threaded program
Arc<T>manymanythe same, when threads are involved
Mutex<T>manyletting one thread at a time change the value
RefCell<T>one onlychanging a value that is shared through an Rc
src/main.rsrust
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    // Box: one owner, value on the heap.
    let boxed = Box::new(5);
    println!("box: {}", *boxed + 1);

    // Rc: several owners in one thread (counted, not thread-safe).
    let shared = Rc::new(String::from("shared text"));
    let other = Rc::clone(&shared);
    println!("rc: {} owners, {}", Rc::strong_count(&shared), other);

    // Arc + Mutex: several owners across threads, one writer at a time.
    let counter = Arc::new(Mutex::new(0));
    let handles: Vec<_> = (0..4)
        .map(|_| {
            let counter = Arc::clone(&counter);
            thread::spawn(move || {
                *counter.lock().unwrap() += 1;
            })
        })
        .collect();
    for h in handles {
        h.join().unwrap();
    }
    println!("arc: {}", *counter.lock().unwrap());
}
text
box: 6
rc: 2 owners, shared text
arc: 4

Why it works#

Rc and Arc keep a count of owners and free the value when the count reaches zero. Rc counts without synchronization, so it is faster, and the compiler refuses to send it to another thread. Arc uses atomic operations, so it can cross threads. A shared value is read-only unless it sits inside a Mutex, because two threads changing the same data at once would be a data race.

Common mistakes#

  • Using Arc<Mutex<T>> by reflex. Often a channel (std::sync::mpsc) or giving each thread its own part of the data is simpler.
  • Holding a MutexGuard across a long operation. The lock is released when the guard goes out of scope, so keep that scope small.
  • Building reference cycles with Rc, which are never freed. Use Weak for the back-pointer.

Does Rust have a garbage collector?#

No: memory is freed when the owner goes out of scope, and Rc and Arc free theirs when the last owner goes.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet