How do I destructure a vector without taking a slice?

12,752

Solution 1

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.

Solution 2

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
Share:
12,752

Related videos on Youtube

Peter Horne
Author by

Peter Horne

Updated on June 04, 2022

Comments

  • Peter Horne
    Peter Horne almost 2 years

    I can destructure a vector of tuples by taking a slice of a vector and references to the items within the tuple:

    let items = vec![("Peter".to_string(), 180)];
    
    if let [(ref name, ref age)] = items.as_slice() {
        println!("{} scored {}", name, age);
    };
    

    How can I destructure the vector directly, moving the items out of the tuple. Something like this:

    let items = vec![("Peter".to_string(), 180)];
    
    if let [(name, age)] = items {
        println!("{} scored {}", name, age);
    };
    

    Compiling the above results in the error:

    error[E0529]: expected an array or slice, found `std::vec::Vec<(std::string::String, {integer})>`
     --> src/main.rs:4:12
      |
    4 |     if let [(name, age)] = items {
      |            ^^^^^^^^^^^^^ pattern cannot match with input type `std::vec::Vec<(std::string::String, {integer})>`
    
  • Admin
    Admin about 9 years
    And even if you could, you probably shouldn't and wouldn't want to mess with the pointer directly.
  • uwu
    uwu about 9 years
    sure, just demonstrate how to match a Vec
  • Peter Horne
    Peter Horne about 9 years
    Thanks! It's a shame that moving items out of a vector can't be supported by the compiler transferring ownership in the same way as it does when destructuring the item tuple.
  • Shepmaster
    Shepmaster about 9 years
    @PeterHorne I'm not sure what you mean. If foo = vec[0] transferred ownership out of the vector and into the variable foo, what would you want vec[0] to mean after the ownership was transferred?
  • Peter Horne
    Peter Horne about 9 years
    Same as if you try to access items after (a, b) = items – an error (use of partially moved value)
  • Matthieu M.
    Matthieu M. about 9 years
    @PeterHorne: You are vastly over-estimating the Rust type system of the moment though. Partial Moves are only available for structures for which the Drop trait is not implemented (see is.gd/tRTWDR => cannot move out of type Person, which defines the Drop trait), because then the compiler cannot know what the Drop trait will rely on.
  • Penz
    Penz over 2 years
    If you do need to use .remove(0), changing the data structure to a VecDeque and using .pop_front() will give you better performance, and no panic.