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?
elem.to_ref()
which is nicer than&**
. – Principle