如何在保持对 self 的引用的同时调用变异方法? [英] How can I call a mutating method while holding a reference to self?

查看:46
本文介绍了如何在保持对 self 的引用的同时调用变异方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在借阅检查器上遇到了困难.

I'm having a hard time with the borrow checker.

for item in self.xxx.iter() {
    self.modify_self_but_not_xxx(item);
}

上面的代码运行之前我将一些代码重构为modify_self_but_not_xxx():

The above code worked before I refactored some code into modify_self_but_not_xxx():

error: cannot borrow `*self` as mutable because `self.xxx` is also borrowed as immutable

如何在持有对 self 的引用的同时调用变异方法(例如,从 for 循环中)?

How can I call a mutating method while holding a reference to self (e.g. from within a for-loop)?

推荐答案

如何在持有对 self 的引用的同时调用变异方法(例如,从 for 循环中)?

How can I call a mutating method while holding a reference to self (e.g. from within a for-loop)?

你不能,这正是借用规则所禁止的.

You can't, that's exactly what the borrowing rules prevent.

主要思想是,在您的代码中,借用检查器不可能知道 self.modify_self_but_not_xxx(..) 不会修改 xxx.

The main idea is that in your code, the borrow checker cannot possibly know that self.modify_self_but_not_xxx(..) will not modify xxx.

但是,您可以改变 self.yyy 或任何其他参数,因此您可以:

However, you can mutate self.yyy or any other parameters, so either you can:

  • 直接在循环体中计算modify_self_but_not_xxx(..)
  • 定义一个使用可变引用来更新它们的辅助函数:

  • do the computations of modify_self_but_not_xxx(..) directly in your loop body
  • define a helper function taking mutable references to update them:

fn do_computations(item: Foo, a: &mut Bar, b: &mut Baz) { /* ... */ }

/* ... */

for item in self.xxx.iter() {
    do_computations(item, &mut self.bar, &mut self.baz);
}

  • 定义一个具有辅助方法的辅助结构
  • 这篇关于如何在保持对 self 的引用的同时调用变异方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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