如何在从成员函数调用的闭包中修改 self ? [英] How can I modify self in a closure called from a member function?

查看:20
本文介绍了如何在从成员函数调用的闭包中修改 self ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算合法的国际象棋移动,但在满足借位检查器的要求时遇到了问题.我有一个实现这些方法的结构 Chess(非重要代码被 ... 替换):

I am trying to calculate legal chess moves and am having problems satisfying the borrow checker. I have a struct Chess that implements these methods (non-important code replaced by ...):

// 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 中遇到编译错误,因为我在闭包内修改 selfget_moves 仍在借用 self.

I get a compilation error in get_legal_moves because I am modifying self inside the closure while get_moves is still borrowing self.

我创建了一个简单的例子来展示我要解决的问题:

I created a simplified example showing the problem I am trying to solve:

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:5
   |
17 |       tester.traverse(|| {
   |       ^      -------- -- first mutable borrow occurs here
   |       |      |
   |  _____|      first borrow later used by call
   | |
18 | |         tester.x += 1; //I want to be able to modify tester here
   | |         ------ first borrow occurs due to use of `tester` in closure
19 | |     });
   | |______^ second mutable borrow occurs here

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 borrow later used by call
   |     first mutable borrow occurs here
18 |         tester.x += 1; //I want to be able to modify tester here
   |         ------ second borrow occurs due to use of `tester` in closure

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

How can I satisfy the borrow checker so the code can compile?

推荐答案

你能做的最简单的改变就是将引用传递给闭包:

The simplest change you can make is to pass the reference to the closure:

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 中是不允许的.

This prevents having multiple mutable references (also known as aliasing), which are disallowed in Rust.

这篇关于如何在从成员函数调用的闭包中修改 self ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆