How to do it...

  1. In the folder bin, create a file called drop.rs.

  2. 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 fn drop(&mut self) {
26 println!("Dropping CustomSmartPointer with data `{:?}`",
self.data);
27 }
28 }
29
30 fn main() {
31 let a = CustomSmartPointer::new("A");
32 let b = CustomSmartPointer::new("B");
33 let c = CustomSmartPointer::new("C");
34 let d = CustomSmartPointer::new("D");
35
36 // The next line would cause a compiler error,
37 // as destructors cannot be explicitely called
38 // c.drop();
39
40 // The correct way to drop variables early is the following:
41 std::mem::drop(c);
42 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.29