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`