且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

方法返回具有相同生存期的结构迭代器的生存期

更新时间:2022-06-27 00:20:11

当方法中存在此类问题时,要做的一件好事就是为&self添加明确的生存期:

When you have this kind of issue in a method, a good thing to do is to add an explicit lifetime to &self:

pub fn neighbors(&'a self) -> impl Iterator<Item = Point<'a>> {
    [(0, -1), (-1, 0), (1, 0), (1, 0)]
        .iter().map(|(dx, dy)| Point {
            board: self.board,
            x: self.x + dx,
            y: self.y + dy,
        })
}

现在的错误更好了

error[E0373]: closure may outlive the current function, but it borrows `self`, which is owned by the current function
  --> src/main.rs:14:30
   |
14 |             .iter().map(|(dx, dy)| Point {
   |                         ^^^^^^^^^^ may outlive borrowed value `self`
15 |                 board: self.board,
   |                        ---- `self` is borrowed here
help: to force the closure to take ownership of `self` (and any other referenced variables), use the `move` keyword
   |
14 |             .iter().map(move |(dx, dy)| Point {
   |                         ^^^^^^^^^^^^^^^

然后,您只需要按照编译器的建议添加move关键字,即可告诉您不再使用&'a self.

You then just need to add the move keyword as advised by the compiler, to say to it that you will not use &'a self again.

请注意,self的生存期不必与Point的生存期相同.***使用以下签名:

Note that the lifetime of self has not to be the same as the lifetime of Point. This is better to use this signature:

fn neighbors<'b>(&'b self) -> impl 'b + Iterator<Item = Point<'a>>