Some Name
Some Name

Reputation: 9540

How to convert Vector of Box to Vector of reference?

I'm looking for a way to conver Vec<Box<u32>> to Vec<&u32>. Here is what I tried:

fn conver_to_ref(){
    let test: Vec<Box<u32>> = vec![Box::new(1), Box::new(2)];
    let _test2: Vec<&u32> = test.into_iter().map(|elem| &*elem).collect();
}

Unfortunately it does not compile: demo. The error message:

error[E0515]: cannot return reference to local data `*elem`
 --> src/lib.rs:3:57
  |
3 |     let _test2: Vec<&u32> = test.into_iter().map(|elem| &*elem).collect();
  |                                                         ^^^^^^ returns a reference to data owned by the current function

How to do such conversion?

Upvotes: 5

Views: 1675

Answers (1)

user4815162342
user4815162342

Reputation: 155296

into_iter() consumes the original vector and its items. If the code compiled as written, all the references in _test2 would be dangling because the boxes would be destroyed along with test.

You can build a vector of references, but you will need to not consume the original test vector, so that the boxes retain an owner. You can simply use iter() instead of into_iter():

fn convert_to_ref() {
    let test: Vec<Box<u32>> = vec![Box::new(1), Box::new(2)];
    let _test2: Vec<&u32> = test.iter().map(Box::as_ref).collect();
}

Note that test.iter() yields references to test elements, i.e. to the boxes themselves (&Box<u32>), and not to the boxed items (&u32) which we're interested in. This is why we must apply as_ref to get the latter.

Upvotes: 7

Related Questions