我正在尝试建立Element
的网格,以便每个Element
都可以引用其邻居。
我的Element
看起来像
struct Element<'a> {
value: u32,
neighbors: Vec<&'a Element<'a>>,
}
这Element
存储在2d Vec中,例如
struct Vec2D<'a> {
vec_2d: Vec<Element<'a>>,
col: usize,
}
在计算邻居时,我试图存储每个邻居对其邻居的引用。
fn calculate_neighbors(&mut self) {
let col = self.col as isize;
let mut indices = Vec::new();
let i = (self.vec_2d.len() - 1) as isize;
if i % col == 0 {
// left edge
//Im doing a bunch of inserts here. Refer Rust playgroud link
} else if (i + 1) % col == 0 {
//right edge
//Im doing a bunch of inserts here. Refer Rust playgroud link
} else {
//middle
//Im doing a bunch of inserts here. Refer Rust playgroud link
}
let valid_neighbors_indices: Vec<usize> = indices.into_iter().map(|e| e as usize).filter(|e| *e < self.vec_2d.len() && *e >= 0).collect();
println!("{} => {:?}", i, valid_neighbors_indices);
let last_element = self.vec_2d.last_mut().unwrap(); //last must be there.
valid_neighbors_indices.into_iter().for_each(|e| {
let neighbor = self.vec_2d.get_mut(e).unwrap(); //all indices in valid_neighbors_indices are valid. so unwrap() is fine.
// Following two lines are problematic:
last_element.neighbors.push(neighbor);
neighbor.neighbors.push(last_element);
});
}
我遇到了一个大错误,即使花了很多时间也无法解决它。
有人可以解释错误并解决吗?