[][src]Function replace_with::replace_with_and_return

pub fn replace_with_and_return<T, U, D: FnOnce() -> T, F: FnOnce(T) -> (U, T)>(
    dest: &mut T,
    default: D,
    f: F
) -> U

Temporarily takes ownership of a value at a mutable location, and replace it with a new value based on the old one. Lets the closure return a custom value as well.

We move out of the reference temporarily, to apply a closure f, returning a new value, which is then placed at the original value's location.

This is effectively the same function as replace_with, but it lets the closure return a custom value as well.

An important note

On panic (or to be more precise, unwinding) of the closure f, default will be called to provide a replacement value. default should not panic – doing so will constitute a double panic and will most likely abort the process.

Example


fn take<T>(option: &mut Option<T>) -> Option<T> {
    replace_with_and_return(option, || None, |option| (option, None))
}

let mut opt = Some(3);
assert_eq!(take(&mut opt), Some(3));
assert_eq!(take(&mut opt), None);