Smart pointers help manage memory safely by automatically cleaning up when no longer needed. They keep track of who owns data so you don't have to worry about mistakes.
Ownership with smart pointers in Rust
let smart_pointer = SmartPointerType::new(data);Common smart pointers in Rust include Box, Rc, and RefCell.
Box owns data uniquely on the heap, Rc allows multiple owners, and RefCell allows mutation inside immutable owners.
Box stores the value 5 on the heap with unique ownership.let b = Box::new(5);
Rc allows multiple owners of the value 10 by cloning the pointer, not the data.use std::rc::Rc; let rc1 = Rc::new(10); let rc2 = Rc::clone(&rc1);
RefCell allows changing data even if the owner is immutable.use std::cell::RefCell; let data = RefCell::new(7); *data.borrow_mut() += 1;
This program shows how Rc smart pointer allows multiple owners of the same string. It prints the number of owners and the values.
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 after clones: {}", Rc::strong_count(&a));
println!("a: {}, b: {}, c: {}", a, b, c);
}Smart pointers automatically free memory when no owners remain.
Using Rc is for shared ownership but is not thread-safe; use Arc for threads.
RefCell allows mutation checked at runtime, so be careful to avoid borrow errors.
Smart pointers manage ownership and memory safely.
Box for unique ownership, Rc for shared ownership, RefCell for interior mutability.
They help prevent bugs by automating cleanup and enforcing rules.
Practice
Solution
Step 1: Understand ownership types
Boxprovides unique ownership,Rcallows shared ownership in single-threaded contexts,RefCellallows interior mutability, andArcis for shared ownership across threads.Step 2: Identify shared ownership in single-threaded code
Rcis the smart pointer designed for multiple owners in single-threaded programs.Final Answer:
Rc-> Option CQuick Check:
Shared ownership =Rc[OK]
- Confusing Box with shared ownership
- Thinking RefCell shares ownership
- Mixing Arc with single-threaded Rc
Box smart pointer holding the integer 10?Solution
Step 1: Recall Box creation syntax
The correct way to create a Box is usingBox::new(value).Step 2: Check each option
let b = Box::new(10);usesBox::new(10), which is correct. Options A, C, and D use invalid syntax.Final Answer:
let b = Box::new(10); -> Option AQuick Check:
Box creation = Box::new(value) [OK]
- Using Box(10) instead of Box::new(10)
- Trying new Box(10) like other languages
- Using non-existent Box::create method
use std::rc::Rc;
let a = Rc::new(5);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));Solution
Step 1: Understand Rc cloning
Cloning anRcpointer increases the reference count but does not clone the data.Step 2: Count strong references
Initially,ahas a count of 1. Afterb = Rc::clone(&a), the count becomes 2.Final Answer:
2 -> Option BQuick Check:
Rc clone increments count = 2 [OK]
- Thinking Rc::clone copies data
- Expecting count to remain 1
- Confusing Rc with Box ownership
RefCell:use std::cell::RefCell;
let data = RefCell::new(10);
let r1 = data.borrow_mut();
let r2 = data.borrow_mut();
println!("{} {}", r1, r2);Solution
Step 1: Understand RefCell borrowing rules
RefCellallows mutable borrowing at runtime but only one mutable borrow at a time.Step 2: Analyze the code
The code tries to create two mutable borrowsr1andr2simultaneously, which causes a runtime panic.Final Answer:
Cannot borrow mutably twice at the same time -> Option AQuick Check:
RefCell mutable borrow rule = one at a time [OK]
- Thinking RefCell forbids integers
- Assuming multiple mutable borrows are allowed
- Confusing compile-time and runtime borrow checks
Solution
Step 1: Understand ownership in tree structures
Children own their data, soRcis used for shared ownership of children nodes.Step 2: Avoid reference cycles
Parents are referenced by children, but to avoid cycles, parents should be referenced withWeakpointers.Step 3: Combine smart pointers correctly
UsingRcfor children andWeakfor parents prevents memory leaks and ownership errors.Final Answer:
Use Rc for children and Weak for parent references -> Option DQuick Check:
Tree ownership = Rc children + Weak parents [OK]
- Using Box for parent causes ownership conflicts
- Using Rc for parents causes reference cycles
- Ignoring Weak pointers to break cycles
Ready to prove it?
Pass the test and this pattern moves unknown
