about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorMark Simulacrum <mark.simulacrum@gmail.com>2017-05-24 19:50:06 -0600
committerGitHub <noreply@github.com>2017-05-24 19:50:06 -0600
commitca0860df66dc92b85659a0d82c8be5868a46c924 (patch)
treef0102590a34720b2a01b096e5d449df2d8931cc0 /src/libcore
parentd64dddbeafb0a41158b2338c7f5e8e355a4aa0e1 (diff)
parentb41b2947d56ce8be0b927d59d766a23271b9dd37 (diff)
downloadrust-ca0860df66dc92b85659a0d82c8be5868a46c924.tar.gz
rust-ca0860df66dc92b85659a0d82c8be5868a46c924.zip
Rollup merge of #42159 - Havvy:doc-drop, r=steveklabnik
Document drop more.

Adds two examples to Drop and describes the recursive drop on types that contain fields.
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/ops.rs44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs
index 59c3a9a8afa..c76cff4dc34 100644
--- a/src/libcore/ops.rs
+++ b/src/libcore/ops.rs
@@ -153,6 +153,13 @@ use marker::Unsize;
 /// The `Drop` trait is used to run some code when a value goes out of scope.
 /// This is sometimes called a 'destructor'.
 ///
+/// When a value goes out of scope, if it implements this trait, it will have
+/// its `drop` method called. Then any fields the value contains will also
+/// be dropped recursively.
+///
+/// Because of the recursive dropping, you do not need to implement this trait
+/// unless your type needs its own destructor logic.
+///
 /// # Examples
 ///
 /// A trivial implementation of `Drop`. The `drop` method is called when `_x`
@@ -171,6 +178,43 @@ use marker::Unsize;
 ///     let _x = HasDrop;
 /// }
 /// ```
+///
+/// Showing the recursive nature of `Drop`. When `outer` goes out of scope, the
+/// `drop` method will be called first for `Outer`, then for `Inner`. Therefore
+/// `main` prints `Dropping Outer!` and then `Dropping Inner!`.
+///
+/// ```
+/// struct Inner;
+/// struct Outer(Inner);
+///
+/// impl Drop for Inner {
+///     fn drop(&mut self) {
+///         println!("Dropping Inner!");
+///     }
+/// }
+///
+/// impl Drop for Outer {
+///     fn drop(&mut self) {
+///         println!("Dropping Outer!");
+///     }
+/// }
+///
+/// fn main() {
+///     let _x = Outer(Inner);
+/// }
+/// ```
+///
+/// Because variables are dropped in the reverse order they are declared,
+/// `main` will print `Declared second!` and then `Declared first!`.
+///
+/// ```
+/// struct PrintOnDrop(&'static str);
+///
+/// fn main() {
+///     let _first = PrintOnDrop("Declared first!");
+///     let _second = PrintOnDrop("Declared second!");
+/// }
+/// ```
 #[lang = "drop"]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub trait Drop {