What is the exact error the compiler is giving you? I think the example above has an extra mut
with the let
, meaning that the value bound to peak
can be reassigned. The peak
variable also might need to be dereferenced to be used:
*peak.intensity += x;
It seems to be pretty common practice to just open new blocks just to borrow something and have the borrow go out of scope before continuing. Something like this: https://is.gd/MP3Qi5
You’re problem may be more difficult if you are trying to borrow multiple fields at once, I think I saw a note about trying to improve that in future releases.
The other thing to look at are having helper methods that mutably borrow the whole struct and then give it back. If what you’re working with are large objects that are just tracking state, can still improve readability somewhat.
impl BigStruct {
fn increment_peak(&mut self, peak_index: usize, amount: u32) {
}
}
...
peak.increment_peak(3, x);