This is a nice pattern that takes the idea of Option::take and extends it to Vec.
/// Replace the value with an "empty" state and return the original value
trait Take {
fn take(&mut self) -> Self;
}
impl<T> Take for Vec<T> {
fn take(&mut self) -> Self {
::std::mem::replace(self, Vec::new())
}
}
This is nice because it allows writing code that replaces a vector with a map of it (playground)
Edited to actually use ownership semantics, where this matters: A vec of Strings for example.
fn update_everything(data: &mut Vec<String>) {
*data = data.take().into_iter().filter_map(|x| {
if x.len() > 5 {
None
} else {
Some(x + " ")
}
}).collect();
}
This method makes the ownership situation in the code easier to understand. I guess replace(&mut foo, Vec::new()) can look like magic to newcomers.
It needs an element with ownership semantics of course, I guess the f32 example missed the mark by a bit.