-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Description
This tracks the stabilization of this function added by PR #61130 in std::mem:
pub fn take<T: Default>(dest: &mut T) -> T {
replace(dest, T::default())
}Original feature request:
I decently often find myself in a position where I have a HashMap, Vec, or some other non-Copy type I want to "take" from its current location, but cannot because I only have &mut self. A particularly common place for this to happen is when finally returning Async::Ready from Future::poll. Usually in these cases, I end up writing:
return Async::Ready(std::mem::replace(self.result, Vec::new()));This works pretty well, since Vec::new does not allocate (as is the case for most collections).
This pattern is common enough that it'd be nice if there was a more standard way to do it. In particular, something like:
mod std::mem {
fn take<T: Default>(t: &mut T) -> T {
std::mem::replace(t, Default::default())
}
}A variant of this was suggested back in #33564, though that modified Default instead, which seems like overkill.
If this is something others agree would be useful, I'd be happy to submit a PR.
EDIT: Changed name from take to swap_default.
EDIT: Changed name back to take.