Im trying to make a grid of Element
s so every Element
can have references to its neighbors.
My Element
looks like
struct Element<'a> {
value: u32,
neighbors: Vec<&'a Element<'a>>,
}
This Element
s are stored in a 2d Vec like
struct Vec2D<'a> {
vec_2d: Vec<Element<'a>>,
col: usize,
}
During neighbor calculation, Im trying to store each neighbors reference to its neighbor.
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);
});
}
I get a big error and even after spending a lot of time I cant resolve it.
Can someone explain the error and fix?
Here is the Rust playground link https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c45e02f1e5bc5ca8b66aa77a41323d44