[−][src]Function replace_with::replace_with_or_default_and_return
pub fn replace_with_or_default_and_return<T: Default, U, F: FnOnce(T) -> (U, T)>(
dest: &mut T,
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. Replaces with Default::default()
on panic.
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_or_default
, 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
, T::default()
will be called to
provide a replacement value. T::default()
should not panic – doing so will constitute a double
panic and will most likely abort the process.
Equivalent to replace_with_and_return(dest, T::default, f)
.
Example
fn take<T>(option: &mut Option<T>) -> Option<T> { replace_with_or_default_and_return(option, |option| (option, None)) }