Newbie, E0499 help please :(

Hi guys, this is a reduced case:

I've been battling with this for a while now, rust playground is telling me
'error: cannot borrow *self as mutable more than once at a time [E0499]'.
I can't see the issue, any help?

if let Some(mut img) = self.images.get_mut(index) { causes self to be mutably borrowed until the corresponding } is encountered. The compiler sees you calling another method on self that takes &mut self, which means that it could end up mutating self.images and invalidate the img pointer that's in use. This is unsafe, so it stops you from doing that.

1 Like

Your load_image method takes two mutable references: self and img. However, it's not possible to get both of these mutable references at the same time, because the img is contained within self (remember, mutable references must be unique).

Do you truly need a mutable reference to some other member of self in load_image? If so, you might need to extract it in a different way:

Is it possible to move load_image method to impl of Image?
impl Image { fn load_image(&mut self, position: u64) {...} }
It seems that E0499 error come from some sort of "incorrect design".

We really need "suggestion to re-design your structure and implentation" rather than error reporting by compiler :slight_smile:

EDIT: Or using remove and insert like this: Rust Playground

Isn't this one of those cases that ought to be tackled in coming versions of the borrow checker?

load_image procedure was designed to read an image from disk which would modify the file stream, image and vector.
It is possible to move the procedure and pass a reference to the file stream, I don't really like that solution so much.

Speed is a concern, it will be used for opengl rendering, so remove and insert is not ideal either :frowning: