2

Is it possible to take ownership of a vector, break it up and take specific items from it?

This does not compile ("cannot move out of index"):

fn main() {
    let mut v: Vec<String> = Vec::with_capacity(400);
    for i in 100..500 { v.push(String::from(i.to_string())); }

    println!("{}", v.len());

    let (a, b) = take_two(v);

    println!("{}", a);
    println!("{}", b);
}

fn take_two(v: Vec<String>) -> (String, String) {
    (v[123], v[321])
}

Playground link

I found it is effectively possible using this contraption:

fn main() {
    let mut v: Vec<String> = Vec::with_capacity(400);
    for i in 100..500 { v.push(String::from(i.to_string())); }

    let (a, b) = take_two(v);

    println!("{}", a);
    println!("{}", b);
}

fn take_two(v: Vec<String>) -> (String, String) {
    let it = v.into_iter();
    let mut it = it.skip(123);
    let a = it.next().unwrap();
    let mut it = it.skip(198);
    let b = it.next().unwrap();

    (a, b)
}

Playground link

Is there a more straightforward way?

AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • [The duplicates applied to your case](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0623d425292ca39d181acefd8503d15c). – Shepmaster Mar 16 '20 at 19:41
  • 1
    This is indeed a duplicate of https://stackoverflow.com/questions/45803990/how-can-i-take-an-item-from-a-vec-in-rust. Can I somehow mark it as such? – AndreKR Mar 16 '20 at 19:42
  • It already is marked as a duplicate. – Shepmaster Mar 16 '20 at 19:48
  • But one of them is bogus, it has nothing to do with ownership and essentially asks how to find if an index is valid. – AndreKR Mar 16 '20 at 19:52
  • "one of them" is ambiguous. Do you mean one of the *questions* or one of the *answers*? If question, you are saying that https://stackoverflow.com/questions/37489004/built-in-safe-way-to-move-out-of-vect is not valid for this question? If answer, then no, there's no such way. – Shepmaster Mar 16 '20 at 19:57
  • 1
    Now that I know the right keywords I actually found *another* question with an answer that applies to my question: https://stackoverflow.com/questions/33204273/how-can-i-take-ownership-of-a-vec-element-and-replace-it-with-something-else – AndreKR Mar 16 '20 at 20:05

0 Answers0