怎么把Box Vector转换成参考Vector?

问题描述

我正在寻找一种将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来获得后者。