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 ofRcacross 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());