Implementing the Drop trait
Where traditional object-oriented languages have destructors, Rust has the Drop
trait, which consists of a single drop
function that is called whenever a variable's lifetime has ended. By implementing it, you can perform whatever cleanup or advanced logging is necessary. You can also automatically free resources via RAII, as we're going to see in the next recipe.
How to do it...
In the folder
bin
, create a file calleddrop.rs
.Add the following code and run it with
cargo run --bin drop
:
1 use std::fmt::Debug; 2 3 struct CustomSmartPointer<D> 4 where 5 D: Debug, 6 { 7 data: D, 8 } 9 10 impl<D> CustomSmartPointer<D> 11 where 12 D: Debug, 13 { 14 fn new(data: D) -> Self { 15 CustomSmartPointer { data } 16 } 17 } 18 19 impl<D> Drop for CustomSmartPointer<D> 20 where 21 D: Debug, 22 { 23 // This will automatically be called when a variable is dropped 24 // It cannot be called manually 25...