2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:34:11 +00:00
|
|
|
date: 2020-09-29
|
2024-05-06 20:40:05 +00:00
|
|
|
id: a5820942-f47a-4a5e-ba83-33916cc24674
|
|
|
|
title: Drop Trait
|
|
|
|
---
|
|
|
|
|
|
|
|
# Introduction
|
|
|
|
|
|
|
|
`Drop` lets you customize what happens when a value is about to go out
|
|
|
|
of scope, ie: to release resources like files or network connections.
|
|
|
|
|
|
|
|
# Example
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
struct CustomSmartPointer {
|
|
|
|
data: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for CustomSmartPointer {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let _c = CustomSmartPointer {
|
|
|
|
data: String::from("my stuff"),
|
|
|
|
};
|
|
|
|
let _d = CustomSmartPointer {
|
|
|
|
data: String::from("other stuff"),
|
|
|
|
};
|
|
|
|
println!("CustomSmartPointers created.");
|
|
|
|
}
|
|
|
|
```
|