Function replace_with::replace_with

source ·
pub fn replace_with<T, F: FnOnce(T) -> T>(dst: &mut T, f: F)
Expand description

Uses f to replace the referent of dst with a new value.

Reads the current value in dst, calls f on that value, and overwrites dst using the new value returned by f. If f panics, the process is aborted.

This is useful for updating a value whose type is not Copy.

§Examples

/// A value that might be stored on the heap (boxed) or on the stack (unboxed).
pub enum MaybeBoxed<T> {
    Boxed(Box<T>),
    Unboxed(T),
}

impl<T> MaybeBoxed<T> {
    /// Ensures that `self` is boxed, moving the value to the heap if necessary.
    pub fn ensure_boxed(&mut self) {
        replace_with(self, |m| match m {
            MaybeBoxed::Boxed(b) => MaybeBoxed::Boxed(b),
            MaybeBoxed::Unboxed(u) => MaybeBoxed::Boxed(Box::new(u)),
        })
    }
}