如何在持有自我引用的同时调用变异方法?

Mar*_*ess 8 rust

借阅检查员我很难过.

for item in self.xxx.iter() {
    self.modify_self_but_not_xxx(item);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作之前,我重构一些代码为modify_self_but_not_xxx():

error: cannot borrow `*self` as mutable because `self.xxx` is also borrowed as immutable
Run Code Online (Sandbox Code Playgroud)

如何在持有引用的同时调用变异方法self(例如从for-loop中引用)?

Lev*_*ans 8

如何在持有引用的同时调用变异方法self(例如从for-loop中引用)?

你不能,这正是借款规则所阻止的.

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

但是,你可以改变self.yyy或任何其他参数,所以你可以:

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

    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);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 定义一个具有辅助方法的辅助结构