3 ms·
What's the idiomatic way to move the self.x+=1 into a separate function? (From the "Function Abstraction" example)
by ufo 4y ago
What's the idiomatic way to move the self.x+=1 into a separate function? (From the "Function Abstraction" example)
- edflsafoiewq 4y agoConstruct references to the fields of self inc needs at the call site and pass those instead of all of self, eg. inc(&mut self.x).
- duped 4y agohttps://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b94daa9a2c2a32b39149b33855c9fa86 https://play.rust-lang.org/?version=stable&mode=debug&editio... But to be honest that's bad code.
- winstonewert 4y agoI've found success in such cases by splitting the struct in question. This example is a bit contrived, but you could do something like: self.counter.inc(); Where `self.counter` is a new struct that holds `x`. Because `counter` is its own struct field, I can call mutable methods on it while holding mutable references to other fields. What I've found is that often the current "object" naturally decomposes into different parts each of which can have their own methods that only need to work with their particular subset of the fields.