[−][src]Function replace_with::replace_with_or_default
pub fn replace_with_or_default<T: Default, F: FnOnce(T) -> T>(
dest: &mut T,
f: F
)
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.
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.
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(dest, T::default, f)
.
Differs from *dest = mem::replace(dest, Default::default())
in that Default::default()
will
only be called on panic.
Example
enum States { A(String), B(String), } impl Default for States { fn default() -> Self { States::A(String::new()) } } impl States { fn poll(&mut self) { replace_with_or_default(self, |self_| match self_ { States::A(a) => States::B(a), States::B(a) => States::A(a), }); } }