From 3431de37d69cb2843c112f88f2810498232b6e21 Mon Sep 17 00:00:00 2001 From: Dylan Maccora Date: Wed, 18 Oct 2017 18:26:56 +1100 Subject: [PATCH] Adding destructor. --- src/scope/raii.md | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/scope/raii.md b/src/scope/raii.md index 481e447407..42413c4813 100644 --- a/src/scope/raii.md +++ b/src/scope/raii.md @@ -2,10 +2,10 @@ Variables in Rust do more than just hold data in the stack: they also *own* resources, e.g. `Box` owns memory in the heap. Rust enforces [RAII][raii] -(Resource Acquisition Is Initialization), so whenever an object goes out of -scope, its destructor is called and its owned resources are freed. +(Resource Acquisition Is Initialization), so whenever an object goes out of +scope, its destructor is called and its owned resources are freed. -This behavior shields against *resource leak* bugs, so you'll never have to +This behavior shields against *resource leak* bugs, so you'll never have to manually free memory or worry about memory leaks again! Here's a quick showcase: ```rust,editable @@ -61,10 +61,36 @@ $ rustc raii.rs && valgrind ./raii No leaks here! +## Destructor + +The notion of a destructor in Rust is provided through the [`Drop`] trait. The +destructor is called when the resource goes out of scope. This trait is not +required to be implemented for every type, only implement it for your type if +you require its own destructor logic. + +Run the below example to see how the [`Drop`] trait works. When the variable in +the `main` function goes out of scope the custom destructor wil be invoked. + +```rust,editable +struct ToDrop; + +impl Drop for ToDrop { + fn drop(&mut self) { + println!("ToDrop is being dropped"); + } +} + +fn main() { + let x = ToDrop; + println!("Made a ToDrop!"); +} +``` + ### See also: [Box][box] [raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization [box]: /std/box.html -[valgrind]: http://valgrind.org/info/ \ No newline at end of file +[valgrind]: http://valgrind.org/info/ +[`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html