Struct DropGuard

struct DropGuard<T, F> { ... }
where
    F: FnOnce(T)

Wrap a value and run a closure when dropped.

This is useful for quickly creating destructors inline.

Examples

# #![allow(unused)]
#![feature(drop_guard)]

use std::mem::DropGuard;

{
    // Create a new guard around a string that will
    // print its value when dropped.
    let s = String::from("Chashu likes tuna");
    let mut s = DropGuard::new(s, |s| println!("{s}"));

    // Modify the string contained in the guard.
    s.push_str("!!!");

    // The guard will be dropped here, printing:
    // "Chashu likes tuna!!!"
}

Implementations

impl<T, F> DropGuard<T, F>

const fn new(inner: T, f: F) -> Self

Create a new instance of DropGuard.

Example

# #![allow(unused)]
#![feature(drop_guard)]

use std::mem::DropGuard;

let value = String::from("Chashu likes tuna");
let guard = DropGuard::new(value, |s| println!("{s}"));
const fn dismiss(guard: Self) -> T
where
    F: 

Consumes the DropGuard, returning the wrapped value.

This will not execute the closure. It is typically preferred to call this function instead of mem::forget because it will return the stored value and drop variables captured by the closure instead of leaking their owned resources.

Example

# #![allow(unused)]
#![feature(drop_guard)]

use std::mem::DropGuard;

let value = String::from("Nori likes chicken");
let guard = DropGuard::new(value, |s| println!("{s}"));
assert_eq!(DropGuard::dismiss(guard), "Nori likes chicken");

impl<P, T> Receiver for DropGuard<T, F>

impl<T> Any for DropGuard<T, F>

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for DropGuard<T, F>

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for DropGuard<T, F>

fn borrow_mut(self: &mut Self) -> &mut T

impl<T> From for DropGuard<T, F>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T, F> Debug for DropGuard<T, F>

fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result

impl<T, F> Deref for DropGuard<T, F>

fn deref(self: &Self) -> &T

impl<T, F> DerefMut for DropGuard<T, F>

fn deref_mut(self: &mut Self) -> &mut T

impl<T, F> Drop for DropGuard<T, F>

fn drop(self: &mut Self)

impl<T, F> Freeze for DropGuard<T, F>

impl<T, F> RefUnwindSafe for DropGuard<T, F>

impl<T, F> Send for DropGuard<T, F>

impl<T, F> Sync for DropGuard<T, F>

impl<T, F> Unpin for DropGuard<T, F>

impl<T, F> UnsafeUnpin for DropGuard<T, F>

impl<T, F> UnwindSafe for DropGuard<T, F>

impl<T, U> Into for DropGuard<T, F>

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom for DropGuard<T, F>

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto for DropGuard<T, F>

fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>