实现自定义迭代器的终身编译器错误。

时间:2019-01-06 08:09:02

标签: rust lifetime

我正在以各种形式实施Conway的《人生游戏》,以重新认识Rust。目前,我正在编写使用迭代器而不是嵌套for循环的实现,并陷入了生命周期问题。

我相信生命周期注释对于迭代器类型是正确的。但是,当我将单元状态绑定到迭代器返回类型时,借位检查器不认为这是有效的分配。我在实现中缺少什么让借项检查器成功?

这是迭代器的当前实现:

struct LifeBoard {
    board_size: usize,
    cells: std::vec::Vec<bool>,
}
struct Cell<'a> {
    row : usize,
    col : usize,
    state : &'a mut bool
}

struct CellIterator<'a> {
    board : &'a mut LifeBoard,
    index : usize
}

impl<'a> std::iter::Iterator for CellIterator<'a> {
    type Item = Cell<'a>;

    fn next(&mut self) -> Option<Cell<'a>> {
        if self.index < self.board.cells.len() {
            let board_size = self.board.board_size;
            let row = self.index / board_size;
            let col = self.index % board_size;
            let state : &'a mut bool =  &mut self.board.cells[self.index];
            self.index = self.index + 1;

            Some( Cell { row, col, state } )
        } else {
            None
        }
    }
}

impl LifeBoard {
    fn new(board_size: usize) -> LifeBoard {
        let mut cells = Vec::new();
        cells.resize(board_size * board_size, false);

        LifeBoard { board_size, cells }
    }

    fn iter_cells_mut( &mut self ) -> CellIterator {
        CellIterator{ board: &mut self, index: 0 }
    }
}

这是错误消息:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
   --> src\main.rs:116:46
    |
116 |             let state : &'a mut bool =  &mut self.board.cells[self.index];
    |                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 109:5...
   --> src\main.rs:109:5
    |
109 | /     fn next(&mut self) -> Option<Cell<'a>> {
110 | |         if self.index < self.board.cells.len() {
111 | |             None
112 | |         } else {
...   |
120 | |         }
121 | |     }
    | |_____^
note: ...so that reference does not outlive borrowed content
   --> src\main.rs:116:46
    |
116 |             let state : &'a mut bool =  &mut self.board.cells[self.index];
    |                                              ^^^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 106:6...
   --> src\main.rs:106:6
    |
106 | impl<'a> std::iter::Iterator for CellIterator<'a> {
    |      ^^
note: ...so that reference does not outlive borrowed content
   --> src\main.rs:116:41
    |
116 |             let state : &'a mut bool =  &mut self.board.cells[self.index];

0 个答案:

没有答案