【发布时间】:2019-06-26 17:16:58
【问题描述】:
我有一个包含两个Vecs 的结构,包裹在RefCells 中。我想在该结构上有一个方法,它结合两个向量并将它们作为新的RefCell 或RefMut 返回:
use std::cell::{RefCell, RefMut};
struct World {
positions: RefCell<Vec<Option<Position>>>,
velocities: RefCell<Vec<Option<Velocity>>>,
}
type Position = i32;
type Velocity = i32;
impl World {
pub fn new() -> World {
World {
positions: RefCell::new(vec![Some(1), None, Some(2)]),
velocities: RefCell::new(vec![None, None, Some(1)]),
}
}
pub fn get_pos_vel(&self) -> RefMut<Vec<(Position, Velocity)>> {
let mut poses = self.positions.borrow_mut();
let mut vels = self.velocities.borrow_mut();
poses
.iter_mut()
.zip(vels.iter_mut())
.filter(|(e1, e2)| e1.is_some() && e2.is_some())
.map(|(e1, e2)| (e1.unwrap(), e2.unwrap()))
.for_each(|elem| println!("{:?}", elem));
}
}
fn main() {
let world = World::new();
world.get_pos_vel();
}
如何将向量的压缩内容作为新的RefCell 返回?这可能吗?
我知道有RefMut::map(),我尝试将两个调用嵌套到map,但没有成功。
【问题讨论】:
-
此外,您的
.filter().map()可能应该只是.filter_map并避免unwraps。 -
抱歉,当我发布这个时,我的大脑已经融化了。我提供了一个无法编译的最小示例,但我认为显示了我尝试做的事情。您链接的其他答案对这个特定问题没有帮助。
-
我同意这个答案:如果你想返回一个新的
Vec,它不需要包裹在任何Ref*中。你为什么认为你想要这样的签名? -
@Shepmaster 这与
Vec无关。我想返回对这些 vecs 中元素的可变引用。而且我看不出有任何方法可以做到这一点。答案创建了一个新的Vec,其中包含新的复制元素,而不是引用。如果调用者更改返回的Vec中的值,则World中的该值不会更改。