How do I destructure a vector without taking a slice?

You are asking two disjoint questions at once:

  1. How can I move out of a vector?
  2. How can I destructure an item?

The second is easy:

let item = ("Peter".to_string(), 180);
let (name, score) = item;

You don't need the if let syntax because there no way for this pattern-matching to fail. Of course, you can't use item after destructuring it because you've transferred ownership from item to name and score.

The first question is harder, and gets to a core part of Rust. If you transfer ownership out of a vector, then what state is the vector in? In C, you would have some undefined chunk of memory sitting in the vector, waiting to blow apart your program. Say you called free on that string, then what happens when you use the thing in the vector that pointed to the same string?

There are a few ways to solve it...

The vector continues to own the items

let items = vec![("Peter".to_string(), 180)];

if let Some((name, score)) = items.first() {
    println!("{} scored {}", name, score);
}

Here, we grab a reference to the first item and then references to the name and score. Since the vector may not have any items, it returns an Option, so we do use if let. The compiler will not let us use these items any longer than the vector lives.

Transfer one element's ownership from the vector

let mut items = vec![("Peter".to_string(), 180)];

let (name, score) = items.remove(0); // Potential panic!
println!("{} scored {}", name, score);

Here, we remove the first item from the array. The vector no longer owns it, and we can do whatever we want with it. We destructure it immediately. items, name and score will all have independent lifetimes.

Transfer all element ownership from the vector

let items = vec![("Peter".to_string(), 180)];

for (name, score) in items {
    println!("{} scored {}", name, score);
}

Here, we consume the vector, so it is no longer available to use after the for loop. Ownership of name and score is transferred to the variables in the loop binding.

Clone the item

let items = vec![("Peter".to_string(), 180)];

let (name, score) = items[0].clone(); // Potential panic!
println!("{} scored {}", name, score);

Here, we make new versions of the items in the vector. We own the new items, and the vector owns the original ones.


You can't do this, the definition of Vec in std is

pub struct Vec<T> {
    ptr: Unique<T>,
    len: usize,
    cap: usize,
}

so you can't match it directly, only:

match xs {
    Vec { ptr: x, .. } => {...}
} 

but

error: field `ptr` of struct `collections::vec::Vec` is private