Rust — Smart Pointers
Box<T>
fn main() {
let b = Box::new(5);
println!("Value: {}", b);
// Recursive type
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
}
Rc<T>
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("Hello"));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Count: {}", Rc::strong_count(&a)); // 3
println!("{} {} {}", a, b, c);
}
RefCell<T>
use std::cell::RefCell;
fn main() {
let data = RefCell::new(vec![1, 2, 3]);
// Borrow mutably at runtime
data.borrow_mut().push(4);
// Borrow immutably
println!("{:?}", data.borrow());
}
Rc<RefCell<T>>
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
let mut data = shared.borrow_mut();
data.push(4);
drop(data);
println!("{:?}", shared.borrow());
}
Weak<T>
use std::rc::{Rc, Weak};
fn main() {
let strong = Rc::new(String::from("Hello"));
let weak: Weak<String> = Rc::downgrade(&strong);
// Upgrade to strong reference
if let Some(value) = weak.upgrade() {
println!("Value: {}", value);
}
}
Mini Practice
Write Rust code that:
- Uses
Boxfor heap allocation - Uses
Rcfor shared ownership - Uses
RefCellfor interior mutability - Combines
Rc<RefCell<T>>
Up Next
In the next lesson, you'll learn about Concurrency — threads and async.
Related Topics
Frequently Asked Questions about Smart Pointers
What is Smart Pointers in Rust?
Smart Pointers is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Smart Pointers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Smart Pointers.
Why is Smart Pointers important in Rust?
Smart Pointers is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.