编译器无法推断生命周期

时间:2020-10-26 23:10:58

标签: rust lifetime

我正在尝试建立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);
        });
    }

我遇到了一个大错误,即使花了很多时间也无法解决它。

有人可以解释错误并解决吗?

这是Rust游乐场链接https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c45e02f1e5bc5ca8b66aa77a41323d44

0 个答案:

没有答案