Summary - Smart pointers
- Rust course
- Intermediate
- Lesson 35/115
- 5 min
Combine Box and Rc to build a tree data structure.
Smart pointers summary
Smart pointers are types that keep data on the heap and carry extra behaviour. Box<T>: single owner, for recursive types and dyn Trait. Rc<T>: shared ownership on a single thread. Arc<T>: shared ownership across threads. Deref lets them be used like the value they hold, and Drop does cleanup at the end of the scope.
The Drop trait
Drop defines code to run when a value is dropped: closing a file, ending a connection, releasing a lock. It isn't called by hand; to drop early, the drop(x) function is used:
struct Kaynak {
ad: &'static str,
}
impl Drop for Kaynak {
fn drop(&mut self) {
println!("kapatıldı: {}", self.ad);
}
}This pattern is called RAII: the resource is tied to the lifetime of the value holding it and becomes impossible to forget.
Practice Drop order
Write the Kaynak type above and its Drop implementation. In main, create _a ("a"); in an inner block create _b ("b") and print iç blok; after the block print son.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Kaynak {
ad: &'static str,
}
impl Drop for Kaynak {
fn drop(&mut self) {
println!("kapatıldı: {}", self.ad);
}
}
fn main() {
let _a = Kaynak { ad: "a" };
{
let _b = Kaynak { ad: "b" };
println!("iç blok");
}
println!("son");
}Expected output
iç blok kapatıldı: b son kapatıldı: a
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In what order are values dropped from a scope?
- In reverse order of declaration Correct answer
- In order of declaration
- Randomly
- By size
Explanation: Since a later value may depend on an earlier one, it is dropped first (stack order).
2 Cleanup method
impl Drop for Kaynak {
fn drop(____) {
println!("kapatıldı: {}", self.ad);
}
}
impl Drop for Kaynak {
fn drop(&mut self) {
println!("kapatıldı: {}", self.ad);
}
}
Explanation: Drop::drop takes &mut self.
3 Type and use case
| Term | Meaning |
|---|---|
Box<T> |
Recursive type |
Rc<T> |
Sharing a graph node |
Arc<T> |
Data across threads |
impl Drop |
Resource cleanup |