Skip to content

Commit 14b767d

Browse files
committed
Add example of recursive drop to Drop trait.
1 parent 81734e0 commit 14b767d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libcore/ops.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,8 @@ use marker::Unsize;
153153
/// The `Drop` trait is used to run some code when a value goes out of scope.
154154
/// This is sometimes called a 'destructor'.
155155
///
156+
///
157+
///
156158
/// # Examples
157159
///
158160
/// A trivial implementation of `Drop`. The `drop` method is called when `_x`
@@ -171,6 +173,32 @@ use marker::Unsize;
171173
/// let _x = HasDrop;
172174
/// }
173175
/// ```
176+
///
177+
/// Showing the recursive nature of `Drop`. When `outer` goes out of scope, the
178+
/// `drop` method will be called for `Outer` and then the `drop` method for
179+
/// `Inner` will be called. Therefore `main` prints `Dropping Outer!` and then
180+
/// `Dropping Inner!`.
181+
///
182+
/// ```
183+
/// struct Inner;
184+
/// struct Outer(Inner);
185+
///
186+
/// impl Drop for Inner {
187+
/// fn drop(&mut self) {
188+
/// println!("Dropping Inner!");
189+
/// }
190+
/// }
191+
///
192+
/// impl Drop for Outer {
193+
/// fn drop(&mut self) {
194+
/// println!("Dropping Outer!");
195+
/// }
196+
/// }
197+
///
198+
/// fn main() {
199+
/// let _x = Outer(Inner);
200+
/// }
201+
/// ```
174202
#[lang = "drop"]
175203
#[stable(feature = "rust1", since = "1.0.0")]
176204
pub trait Drop {

0 commit comments

Comments
 (0)