Code readability for complex structs


Dear all,

I would like to ask if there is a way to enhance code readability if using complex structs. The thing is that I have a mutably borrowed struct and cannot mutably borrow it again. Otherwise, I would just borrow it to a new name and use this as alias.

// this does not work for a borrowed struct `peak`
let mut peak = &mut mr.spectrum.peaks[index_peak];
peak.intensity += x;

I appreciate any suggestions.

Thx, Ronny


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:

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


Thanks for the reply. I cannot reconstruct the example right now. Your example is working. Let’s see… if I have this problem again, I’ll make a new post :wink: