Smart Pointers (Box, Rc, RefCell)Intermediate
1Question 1 of 1
rustWhat are Rust Smart Pointers (Box, Rc, RefCell, Arc)?
Explanation & Concept
Smart pointers provide extra capabilities beyond simple references:
• `Box<T>`: Allocates data on the heap (used for recursive types). • `Rc<T>`: Reference-counted pointer for single-threaded multiple ownership. • `RefCell<T>`: Implements **interior mutability**, deferring borrow checking to runtime. • `Arc<T>`: Atomically Reference Counted pointer for safe multi-threaded sharing.
Code Example
rust
use std::sync::Arc;
use std::thread;
fn main() {
// Arc allows safe sharing across threads
let shared_data = Arc::new(vec![1, 2, 3]);
let data_clone = Arc::clone(&shared_data);
let handle = thread::spawn(move || {
println!("Read from thread: {:?}", data_clone);
});
handle.join().unwrap();
}How It Works & Key Takeaways
`Arc<T>` combined with `Mutex<T>` enables safe concurrent state modification across multiple threads in Rust.
Mock Test · 1 Questions · Optional
Ready for Concurrency & Fearless Threads?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions