Consider the following example program:
struct Data {
output: Vec<u8>,
array: Vec<u8>
}
impl Data {
fn peek(&self) -> u8 {
self.array[0]
}
fn write(&mut self) {
self.output.push(self.peek());
}
}
fn main() {
}
(Ignore the naming of methods; it makes more sense in the larger scope of the actual implementation)
When I try to compile this, I get an error, that I can't borrow from self while self is mutably borrowed.
test.rs:11:26: 11:30 error: cannot borrow
*self
as immutable becauseself.output
is also borrowed as mutable
I understand the concept it is addressing here; what I don't understand is how to get around this. In reality, peek does more than just read the zeroth element, and I don't want to repeat the logic of peek inside write; there must be a way for implementing this in Rust. Write and peek use completely different struct members, so there is zero chance of a race condition here.
I'm very new to Rust, so I wouldn't be surprised if I'm missing something obvious, or if there's a design pattern or best practice I'm violating. Please let me know if that's the case.