Som*_*ame 4 boxing reference vector rust
我正在寻找一种方法来转换Vec<Box<u32>>为Vec<&u32>. 这是我尝试过的:
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();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是它无法编译:demo。错误信息:
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
Run Code Online (Sandbox Code Playgroud)
如何进行这样的转换呢?
into_iter()消耗原始向量及其项目。如果代码按照编写的方式编译,则 中的所有引用都_test2将悬空,因为这些框将与 一起被销毁test。
您可以构建引用向量,但您不需要消耗原始test向量,以便盒子保留所有者。您可以简单地使用iter()而不是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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,test.iter()产生对元素的引用test,即对盒子本身的引用 ( ),而不是对我们感兴趣的&Box<u32>装箱项目 ( ) 的引用。这就是为什么我们必须申请获取后者。&u32as_ref