Rust
Smart Pointers
Box, Rc, RefCell.
By EZ4Code Team
pointersmart-pointer
Code
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::Arc;
fn main() {
// Box: heap allocation
let b = Box::new(5);
println!("Box: {}", b);
// Recursive type
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{:?}", list);
// Rc: reference counting (single-threaded)
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Reference count: {}", Rc::strong_count(&a));
// RefCell: interior mutability
let data = RefCell::new(vec![1, 2, 3]);
data.borrow_mut().push(4);
println!("{:?}", data.borrow());
// Arc: atomic reference counting (multi-threaded)
let arc = Arc::new(Mutex::new(0));
println!("Arc count: {}", Arc::strong_count(&arc));
}
use std::sync::Mutex;Explanation
Box is heap allocation; Rc is single-threaded reference counting; RefCell is runtime borrow checking; Arc is multi-threaded reference counting.