pub fn replace_with_and_return<T, U, D: FnOnce() -> T, F: FnOnce(T) -> (U, T)>(
dest: &mut T,
default: D,
f: F,
) -> U
Expand description
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 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);