# Method .take() on Vec

**URL:** <https://internals.rust-lang.org/t/method-take-on-vec/3371>\
**Category:** libs\
**Created:** [April 13, 2016, 11:16am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371 "2016-04-13T11:16:04Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [April 13, 2016, 11:16am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/1 "2016-04-13T11:16:04Z")

</div>

This is a nice pattern that takes the idea of `Option::take` and extends it to Vec.

```rust

/// 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)](https://play.rust-lang.org/?gist=8d5840a9bf9cccfc38ecc536831e5e31&version=stable&backtrace=0)

_Edited to actually use ownership semantics, where this matters: A vec of Strings for example._

```rust
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.

---

<div class="post-metadata">

**Author:** ![oli-obk](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/oli-obk/32/3168_2.png) [@oli-obk](https://internals.rust-lang.org/u/oli-obk)\
**Post date:** [April 13, 2016, 11:24am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/2 "2016-04-13T11:24:39Z")

</div>

isn’t that simply

```rust
    let d = data.drain(..).filter_map(|x| {
        if x <= 10. {
            Some(x * x)
        } else { None }
    }).collect();
    *data = d;

```

or using [`retain_mut`](https://github.com/rust-lang/rfcs/pull/1353) once that RFC gets through

---

<div class="post-metadata">

**Author:** ![WiSaGaN](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/wisagan/32/4027_2.png) [@WiSaGaN](https://internals.rust-lang.org/u/WiSaGaN)\
**Post date:** [April 13, 2016, 11:29am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/3 "2016-04-13T11:29:39Z")

</div>

I usually use [Vec::split\_off](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.split_off) for this.

```rust
let mut vec = vec![1,2,3];
let vec2 = vec.split_off(0);
assert!(vec.is_empty());
assert_eq!(vec2, [1, 2, 3]);

```

It has the same interface as the `take` you propose.

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [April 13, 2016, 11:45am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/4 "2016-04-13T11:45:28Z")

</div>

retain\_mut is a good alternative, if you want in-place mutation instead of mapping to a new vec.

What I was trying to show is that .take() is nice when you want to consume the vec and then create a new one.

---

<div class="post-metadata">

**Author:** ![petrochenkov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/petrochenkov/32/2784_2.png) [@petrochenkov](https://internals.rust-lang.org/u/petrochenkov)\
**Post date:** [April 13, 2016, 11:47am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/5 "2016-04-13T11:47:07Z")

</div>

This is a trait for C++ style non-destructive move semantics! It would be nice to have such trait in libstd.  
There are plenty of types that can implement it.

---

<div class="post-metadata">

**Author:** ![DanielKeep](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/danielkeep/32/1332_2.png) [@DanielKeep](https://internals.rust-lang.org/u/DanielKeep)\
**Post date:** [April 13, 2016, 2:47pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/6 "2016-04-13T14:47:25Z")

</div>

What about:

```rust
trait Yoink {
    /**
    Yoinks the current value out from under the owner's feet, replacing it with
    the default value... hopefully before anyone notices.
    */
    fn yoink(&mut self) -> Self;
}

impl<T> Yoink for T where T: Default {
    fn yoink(&mut self) -> Self {
        ::std::mem::replace(self, Self::default())
    }
}

```

Then you can `yoink` all sorts of things.

---

<div class="post-metadata">

**Author:** ![oli-obk](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/oli-obk/32/3168_2.png) [@oli-obk](https://internals.rust-lang.org/u/oli-obk)\
**Post date:** [April 13, 2016, 3:39pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/7 "2016-04-13T15:39:10Z")

</div>

Can’t we just implement this as a method on the `Default` trait?

---

<div class="post-metadata">

**Author:** ![DanielKeep](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/danielkeep/32/1332_2.png) [@DanielKeep](https://internals.rust-lang.org/u/DanielKeep)\
**Post date:** [April 13, 2016, 3:41pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/8 "2016-04-13T15:41:15Z")

</div>

Not without being `core`.

---

<div class="post-metadata">

**Author:** ![hanna-kruppe](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hanna-kruppe/32/6540_2.png) [@hanna-kruppe](https://internals.rust-lang.org/u/hanna-kruppe)\
**Post date:** [April 13, 2016, 3:55pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/9 "2016-04-13T15:55:05Z")

</div>

You say that like it’s a problem. `std::mem` is a re-export of `core::mem` so I don’t see why it couldn’t be in libcore.

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [April 13, 2016, 6:41pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/10 "2016-04-13T18:41:09Z")

</div>

It’s sad, but your name is better (HashSet is already using .take() for a different purpose). The nice thing about a less spray-y version is that Vec’s implementation is totally cheap and appropriate for the kind of replace-map-assign transformation, while most other collections are not that nice.

---

<div class="post-metadata">

**Author:** ![troplin](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/troplin/32/1182_2.png) [@troplin](https://internals.rust-lang.org/u/troplin)\
**Post date:** [April 13, 2016, 8:50pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/11 "2016-04-13T20:50:07Z")

</div>

`take` is already quite overloaded:

- `io::Read::take`: Could lead to confusion since `Vec<u8>` implements `Write` and thus may already be used as a kind of stream.
- `iter::Iterator::take`: `Vec` is also very closely related to iterators.

At least those two are the same basic concept.

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [April 14, 2016, 12:16pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/12 "2016-04-14T12:16:07Z")

</div>

Yes. The feature is more important than the name.

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [April 14, 2016, 6:42pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/13 "2016-04-14T18:42:50Z")

</div>

For name-bikeshedding, I suggest `Default::replace_default(&mut self)` – implemented with `mem::replace` as suggested, but of course that can be overridden if any type wants for some reason.

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [May 11, 2016, 7:48pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/14 "2016-05-11T19:48:59Z")

</div>

> <https://github.com/rust-lang/rust/pull/33564>

---

<div class="post-metadata">

**Author:** ![doomrobo](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/doomrobo/32/1595_2.png) [@doomrobo](https://internals.rust-lang.org/u/doomrobo)\
**Post date:** [June 1, 2016, 5:59am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/15 "2016-06-01T05:59:16Z")

</div>

While I agree, I think a more functional approach like in-place mapping or `retain_mut` as you mentioned would be clearer and easier to use. I know at least that I would rather use a higher order function that did everything in place than think about move/copy semantics. Speaking of which, is this code equivalent to your example or is it less efficient?

```rust
fn update_everything(data: &mut Vec<String>) {
    *data = data.into_iter().filter_map(|x| {
        if x.len() > 5 {
            None
        } else {
            Some(x.clone() + " ")
        }
    }).collect();
}

```

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [June 6, 2016, 5:38pm UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/16 "2016-06-06T17:38:16Z")

</div>

It’s less efficient since `.into_iter()` on a `&mut Vec` gives you the same as `iter_mut()`, so `x` is a `&mut String`. Since the string is taken by reference, a full copy of each string is forced, and that’s the overhead.

---

<div class="post-metadata">

**Author:** ![bluss](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bluss/32/2264_2.png) [@bluss](https://internals.rust-lang.org/u/bluss)\
**Post date:** [March 25, 2019, 8:26am UTC](https://internals.rust-lang.org/t/method-take-on-vec/3371/17 "2019-03-25T08:26:03Z")

</div>

Closed on March 25, 2019, 8:26am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
