Skip to content

Commit 0b70378

Browse files
committed
Auto merge of #26664 - steveklabnik:gh26571, r=alexcrichton
This was pretty misleading, so let's improve. Fixes #26571
2 parents f39df49 + f758baa commit 0b70378

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

src/libcore/mem.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,11 +365,48 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
365365

366366
/// Disposes of a value.
367367
///
368-
/// This function can be used to destroy any value by allowing `drop` to take ownership of its
369-
/// argument.
368+
/// While this does call the argument's implementation of `Drop`, it will not
369+
/// release any borrows, as borrows are based on lexical scope.
370370
///
371371
/// # Examples
372372
///
373+
/// Basic usage:
374+
///
375+
/// ```
376+
/// let v = vec![1, 2, 3];
377+
///
378+
/// drop(v); // explicitly drop the vector
379+
/// ```
380+
///
381+
/// Borrows are based on lexical scope, so this produces an error:
382+
///
383+
/// ```ignore
384+
/// let mut v = vec![1, 2, 3];
385+
/// let x = &v[0];
386+
///
387+
/// drop(x); // explicitly drop the reference, but the borrow still exists
388+
///
389+
/// v.push(4); // error: cannot borrow `v` as mutable because it is also
390+
/// // borrowed as immutable
391+
/// ```
392+
///
393+
/// An inner scope is needed to fix this:
394+
///
395+
/// ```
396+
/// let mut v = vec![1, 2, 3];
397+
///
398+
/// {
399+
/// let x = &v[0];
400+
///
401+
/// drop(x); // this is now redundant, as `x` is going out of scope anyway
402+
/// }
403+
///
404+
/// v.push(4); // no problems
405+
/// ```
406+
///
407+
/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
408+
/// seemingly release a borrow of one:
409+
///
373410
/// ```
374411
/// use std::cell::RefCell;
375412
///

0 commit comments

Comments
 (0)