以相同的方法在向量中查找并推送元素

Find and push element in a vector in the same method

我觉得我的实现太麻烦了,我想有更好的方法来实现这个简单的东西。

我有一个代表游戏板的 Grid 结构,我有一个方法可以将一个单元格添加到网格中,这个方法 (add_cell) 检查网格中是否已经存在一个单元格添加它。

struct Cell {
    // A simplified version with only one coordinate
    position: i8,
}

struct Grid {
    // List of cells in the grid
    cells: Vec<Rc<Cell>>,
}

impl Grid {
    // Add a cell in to the grid
    pub fn add_cell(&mut self, cell: Cell) {
        let is_not_yet_in;
        {
            if self.cells.iter().find(|&c| c.position == cell.position).is_some() {
                is_not_yet_in = false;
            } else {
                is_not_yet_in = true;
            }
        }
        if is_not_yet_in {
            self.cells.push(Rc::new(cell).clone());
        }
    }
}

我在 is_not_yet_in 声明之后放置了 fake 作用域,以避免在 self.cells 的 mutable/immutable 借用时出现编译错误。无论如何,我认为可以使用不同的方法来避免这个技巧。

您应该仔细阅读并记住此处 Iterator trait. Specifically, you want any 的方法。我还翻转了你的变量名的极性以匹配。

pub fn add_cell(&mut self, cell: Cell) {
    let is_present = self.cells.iter().any(|c| c.position == cell.position);
    if !is_present {
        self.cells.push(Rc::new(cell).clone());
    }
}

此外,Rc::new(cell).clone() 没有任何意义 — 您不妨将其缩短为 Rc::new(cell)