如何修改从成员函数调用的闭包中的self?

我试图计算合法的棋步,并且遇到了满足借用检查器的问题。 我有一个结构Chess实现这些方法(非重要的代码替换... ):

// internal iterator over (possibly not legal) moves
fn get_moves<F>(&self, func: F)
where
    F: Fn(/* ... */),
{
    func(/* ... */); // move 1
    func(/* ... */); // move 2
    func(/* ... */); // etc...
}

fn is_legal_move(&mut self) -> bool {
    // notice this takes a mutable self. For performance
    // reasons, the move is made, legality is checked, then I
    // undo the move, so it must be mutable to be able to move pieces
    make_move(/* ... */);
    // check if legal
    undo_move(/* ... */);
    //return true if legal
}

fn get_legal_moves(&self) /* -> ... */ {
    self.get_moves(|/* ... */| {
        if self.is_legal_move(/* ... */) { // <-- error here
            // do something with legal move
        }
    })
}

我在get_legal_moves得到了一个编译错误,因为我正在修改关闭内部的self ,而'get_moves'仍在借用self

我创建了一个简化的示例,显示我正在尝试解决的问题:

struct Tester {
    x: i8,
}

impl Tester {
    fn traverse<Func>(&mut self, mut f: Func)
    where
        Func: FnMut(),
    {
        //in real-world, this would probably iterate over something
        f();
    }
}

fn main() {
    let mut tester = Tester { x: 8 };
    tester.traverse(|| {
        tester.x += 1; //I want to be able to modify tester here
    });
    println!("{}", tester.x);
}

操场

错误:

error[E0499]: cannot borrow `tester` as mutable more than once at a time
  --> src/main.rs:17:21
   |
17 |     tester.traverse(|| {
   |     ------          ^^ second mutable borrow occurs here
   |     |
   |     first mutable borrow occurs here
18 |         tester.x += 1; //I want to be able to modify tester here
   |         ------ borrow occurs due to use of `tester` in closure
19 |     });
   |      - first borrow ends here

我怎样才能满足借用检查器,以便代码可以编译?


您可以做的最简单的更改是将引用传递给闭包:

struct Tester {
    x: i8,
}

impl Tester {
    fn traverse<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Tester),
    {
        f(self);
    }
}

fn main() {
    let mut tester = Tester { x: 8 };
    tester.traverse(|z| z.x += 1);
    println!("{}", tester.x);
}

这可以防止在Rust中不允许使用多个可变引用(也称为别名)。

链接地址: http://www.djcxy.com/p/83747.html

上一篇: How can I modify self in a closure called from a member function?

下一篇: MediaRecorder start error codes