Cannot borrow `x` as mutable more than once at a time?

Viewed 1039

Logically this code is correct, However rust doesn't understand the context. Trying to reading some byte from cursor with very short 'lifetime of exclusive reference.

Why this code does not compile? Playground

struct Cursor {
    offset: usize,
    data: [u8; 4],
}
impl Cursor {
    fn read_slice(&mut self, n: usize) -> &[u8] {
        let data = &self.data[self.offset..self.offset + n];
        self.offset += n;
        data
    }
}
struct FooBar<'a> {
    foo: &'a [u8],
    bar: &'a [u8],
}

fn read_foobar_from<'a>(cursor: &'a mut Cursor) -> FooBar<'a> {
    FooBar {
        foo: cursor.read_slice(2),
        bar: cursor.read_slice(2),
    }
}

Error:

error[E0499]: cannot borrow `*cursor` as mutable more than once at a time
  --> src/main.rs:22:14
   |
19 |   fn read_foobar_from<'a>(cursor: &'a mut Cursor) -> FooBar<'a> {
   |                       -- lifetime `'a` defined here
20 | /     FooBar {
21 | |         foo: cursor.read_slice(2),
   | |              -------------------- first mutable borrow occurs here
22 | |         bar: cursor.read_slice(2),
   | |              ^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
23 | |     }
   | |_____- returning this value requires that `*cursor` is borrowed for `'a`
1 Answers

The duplicate I linked as a comment addresses why you get this error. (tl;dr: Rust doesn't downgrade borrows; a function borrowing a value mutably and returning an immutable reference with the same lifetime causes the mutable borrow to exist as long as the returned reference does.)

How might we solve the problem in this case?

When I think "cursor" I don't think "something that owns data and allows reading that data out," I think "something that reads out data owned by something else." It turns out that model can solve this problem by having something else to tie the lifetime of the returned reference to.

If we make Cursor borrow the data instead of owning it, we can denote that the returned reference is bound to the lifetime of that data instead of the mutable borrow of self:

struct Cursor<'a> {
    offset: usize,
    data: &'a [u8],
}
impl<'a> Cursor<'a> {
    fn read_slice(&mut self, n: usize) -> &'a [u8] {
        let data = &self.data[self.offset..self.offset + n];
        self.offset += n;
        data
    }
}

(Playground)

If you want Cursor to own the data then interior mutability (e.g. offset: Cell<usize>) may be your only option:

struct Cursor {
    offset: Cell<usize>,
    data: [u8; 4],
}
impl Cursor {
    fn read_slice(&self, n: usize) -> &[u8] {
        let offset = self.offset.get();

        let data = &self.data[offset..offset + n];
        self.offset.set(offset + n);
        data
    }
}

(Playground)

Related