Skip to content

Commit

Permalink
Rollup merge of rust-lang#42159 - Havvy:doc-drop, r=steveklabnik
Browse files Browse the repository at this point in the history
Document drop more.

Adds two examples to Drop and describes the recursive drop on types that contain fields.
  • Loading branch information
Mark-Simulacrum committed May 23, 2017
2 parents 7e4dda1 + b41b294 commit 20a5a5d
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/libcore/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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 {
Expand Down

0 comments on commit 20a5a5d

Please sign in to comment.