Cannot borrow mutable self when accessing disjoint fields

Hi,

I wanted to confirm if this is expected error in Rust, and if there is a good workaround.

I have 2 fields (f and encrypted_chunk below) in a struct, but it seems that I cannot have one line of code accessing both of them with mut self.

snipped code:

use std::fs::File;

pub struct MyDecryptor {
    f: File,
    encrypted_chunk: Vec<u8>,
}

impl MyDecryptor {
    fn decrypt_next(mut self: Pin<&mut Self>) -> Option<Vec<u8>> {
        match self.f.read(&mut self.encrypted_chunk[..]) {
            Ok(size) => ...

//snipped

The buffer encrypted_chunk is in struct because I don't want to allocate it every time when decrypt_next is called. But now I have the following error:

191 |         match self.f.read(&mut self.encrypted_chunk[..]) {
    |               ----   ----      ^^^^ second mutable borrow occurs here
    |               |      |
    |               |      first borrow later used by call
    |               first mutable borrow occurs here

My understanding is that f and encrypted_chunk are disjoint fields. Why is it not allowed in this case?

I could remove the encrypted_chunk from the struct and allocate it as local buffer every time, but is there a better workaround?

Thanks.

This is because you're accessing self through Pin, which means that this is really:

match self.deref_mut().f.read(&mut self.deref_mut().encrypted_chunk[..]) {

and DerefMut::deref_mut mutably borrows all of self. You'll want to do this instead:

let me = Pin::into_inner(self);
match me.f.read(&mut me.encrypted_chunk[..]) {
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.