Here are several examples demonstrating different smart pointers in Rust:
rust
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use std::ops::Deref;
// Custom smart pointer example
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
// Implementing Deref trait to make it behave like a reference
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// Function that takes a string reference
fn hello(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
// Example 1: Box<T> - heap allocation
let box_example = Box::new(5);
println!("Box contains: {}", box_example);
// Example 2: Custom smart pointer with Deref
let custom_box = MyBox::new(String::from("Rust"));
// Deref coercion: &MyBox<String> -> &String -> &str
hello(&custom_box);
// Example 3: Rc<T> - reference counting for shared ownership
let shared_data = Rc::new(vec![1, 2, 3]);
println!("Reference count after creation: {}", Rc::strong_count(&shared_data));
{
let _shared_data2 = Rc::clone(&shared_data);
println!("Reference count after clone: {}", Rc::strong_count(&shared_data));
// _shared_data2 goes out of scope here
}
println!("Reference count after inner scope: {}", Rc::strong_count(&shared_data));
// Example 4: RefCell<T> - interior mutability
let data = RefCell::new(5);
// We can borrow mutably even though data is not declared as mut
{
let mut mutable_borrow = data.borrow_mut();
*mutable_borrow += 10;
} // mutable_borrow goes out of scope here, releasing the borrow
println!("RefCell now contains: {:?}", data.borrow());
// Example 5: Rc<RefCell<T>> - shared mutable data
let shared_mutable_data = Rc::new(RefCell::new(vec![10, 20, 30]));
let shared_mutable_data2 = Rc::clone(&shared_mutable_data);
// Modify through first reference
shared_mutable_data.borrow_mut().push(40);
// Modify through second reference
shared_mutable_data2.borrow_mut().push(50);
println!("Shared mutable data: {:?}", shared_mutable_data.borrow());
// Example 6: Arc<T> and Mutex<T> - thread-safe shared mutable state
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter_clone = Arc::clone(&counter);
let handle = std::thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final counter value: {}", *counter.lock().unwrap());
}
Explanation of Smart Pointers Used:
Box<T>: The simplest smart pointer that provides heap allocation. When you need to store data on the heap rather than the stack, or when you have a large amount of data and want to transfer ownership without copying.
Custom MyBox<T>: Demonstrates how to implement your own smart pointer with the Deref trait, allowing for deref coercion.
Rc<T> (Reference Counted): Enables multiple ownership by keeping track of the number of references to a value. Used when data needs to be shared but not modified.
RefCell<T>: Provides interior mutability - the ability to mutate data even when there are immutable references to that data. It enforces borrowing rules at runtime instead of compile time.
Rc<RefCell<T>>: A common pattern that combines shared ownership with interior mutability, allowing multiple owners to mutate shared data.
Arc<T> and Mutex<T>: Thread-safe versions for shared ownership and interior mutability:
Arc<T> (Atomic Reference Counted): Thread-safe version of Rc<T>
Mutex<T>: Provides mutual exclusion, ensuring only one thread can access the data at a time
These smart pointers are essential tools in Rust for managing memory, ownership, and concurrency in a safe manner.