如何在保持对 self 的引用的同时调用变异方法? [英] How can I call a mutating method while holding a reference to 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 afor
-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屋!