Of course!
Let's go through a simple example of using a smart pointer in Rust.
Rust has several smart pointers, like:
Box<T> — for heap allocation
Rc<T> — for reference-counted shared ownership
RefCell<T> — for interior mutability
Let's start with a basic example using Box<T>, the simplest smart pointer.
🔹 Example: Using Box<T> to store data on the heap
fn main() {
let b = Box::new(5);
println!("b = {}", b);
}
✅ Explanation:
Box::new(5) allocates an integer 5 on the heap.
b is a smart pointer that points to the heap-allocated value.
- When
b goes out of scope, Rust automatically deallocates the heap memory.
🔹 A slightly more interesting example: Recursive data structure (like a linked list)
Rust needs smart pointers like Box to define recursive types because the size of the type must be known at compile time.
// Define a simple linked list
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("Created a linked list!");
}
✅ Explanation:
List is a recursive enum.
Cons holds an integer and a Box pointing to the next List.
Nil represents the end of the list.
- Without
Box, the compiler would not know how much memory to allocate because the size of a recursive type would be infinite.
🔹 Example: Shared ownership with Rc<T>
If you want multiple parts of your program to own the same data, you can use Rc<T> (Reference Counted).
use std::rc::Rc;
fn main() {
let a = Rc::new(5);
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("a = {}, b = {}, c = {}", a, b, c);
println!("Reference count = {}", Rc::strong_count(&a));
}
✅ Explanation:
Rc::new(5) creates a reference-counted smart pointer.
Rc::clone(&a) creates a new pointer to the same data, increasing the reference count.
Rc::strong_count(&a) shows how many Rc pointers are pointing to the same data.
Would you also like me to show an example using RefCell<T> for interior mutability?
(That's where you can mutate data even when the smart pointer is immutable!) 🚀