Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

rust - 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);
}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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

  • 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);
    }
    
  • define a helper struct that has helper methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...