Skip to main content
InterviewHubPRO
Section Overview
Q37

Question 37 of 50

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

74%
Rust Systems & Tokio (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

Smart Pointers in Rust: `Box`, `Rc`, `Arc`, `RefCell`, and `Mutex`.

senior LevelCode ExamplerustAdvanced Internals

In Simple Words:

  • Box<T>: Allocates data on the heap rather than the stack. Used for recursive data structures with dynamic size.
  • Rc<T>: Reference Counting pointer for single-threaded multiple ownership.
  • Arc<T>: Atomic Reference Counting pointer; thread-safe equivalent of Rc across threads.
  • RefCell<T>: Provides Interior Mutability; enforces borrowing rules at runtime instead of compile time.
  • Arc<Mutex<T>>: Standard pattern for thread-safe shared mutable state across threads.
rust
use std::sync::{Arc, Mutex};
use std::thread;

let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];

for _ in 0..5 {
    let c = Arc::clone(&counter);
    handles.push(thread::spawn(move || {
        let mut num = c.lock().unwrap();
        *num += 1;
    }));
}

for h in handles { h.join().unwrap(); }
println!("Final Count: {}", *counter.lock().unwrap());