Function core::mem::drop [] [src]

pub fn drop<T>(_x: T)

Disposes of a value.

While this does call the argument's implementation of Drop, it will not release any borrows, as borrows are based on lexical scope.

Examples

Basic usage:

fn main() { let v = vec![1, 2, 3]; drop(v); // explicitly drop the vector }
let v = vec![1, 2, 3];

drop(v); // explicitly drop the vector

Borrows are based on lexical scope, so this produces an error:

fn main() { let mut v = vec![1, 2, 3]; let x = &v[0]; drop(x); // explicitly drop the reference, but the borrow still exists v.push(4); // error: cannot borrow `v` as mutable because it is also // borrowed as immutable }
let mut v = vec![1, 2, 3];
let x = &v[0];

drop(x); // explicitly drop the reference, but the borrow still exists

v.push(4); // error: cannot borrow `v` as mutable because it is also
           // borrowed as immutable

An inner scope is needed to fix this:

fn main() { let mut v = vec![1, 2, 3]; { let x = &v[0]; drop(x); // this is now redundant, as `x` is going out of scope anyway } v.push(4); // no problems }
let mut v = vec![1, 2, 3];

{
    let x = &v[0];

    drop(x); // this is now redundant, as `x` is going out of scope anyway
}

v.push(4); // no problems

Since RefCell enforces the borrow rules at runtime, drop() can seemingly release a borrow of one:

fn main() { use std::cell::RefCell; let x = RefCell::new(1); let mut mutable_borrow = x.borrow_mut(); *mutable_borrow = 1; drop(mutable_borrow); // relinquish the mutable borrow on this slot let borrow = x.borrow(); println!("{}", *borrow); }
use std::cell::RefCell;

let x = RefCell::new(1);

let mut mutable_borrow = x.borrow_mut();
*mutable_borrow = 1;

drop(mutable_borrow); // relinquish the mutable borrow on this slot

let borrow = x.borrow();
println!("{}", *borrow);