我正在寻找一种沟通方式 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();
}
不幸的是它无法编译: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
如何进行这样的转换?
最佳答案
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();
}
请注意test.iter()
产生对 test
的引用元素,即盒子本身( &Box<u32>
),而不是我们感兴趣的装箱项目( &u32
)。这就是为什么我们必须应用 as_ref
。得到后者。
关于vector - 如何将盒子向量转换为引用向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63525018/