Skip to content

Tracking issue for std::mem::take #61129

Description

@jonhoo

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    B-unstableBlocker: Implemented in the nightly compiler and unstable.C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-api[DEPRECATED; DO NOT USE]

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions