I have the following code
pub struct Something {
value: usize,
}
impl Something {
pub fn get_and_increment(&mut self) -> &[u8] {
let res = self.get();
self.value += 1;
res
}
pub fn get(&self) -> &[u8] {
&[3; 2]
}
}
When I try to compile this I get this error:
error[E0506]: cannot assign to `self.value` because it is borrowed
--> src/main.rs:8:9
|
7 | let res = self.get();
| ---- borrow of `self.value` occurs here
8 | self.value += 1;
| ^^^^^^^^^^^^^^^ assignment to borrowed `self.value` occurs here
If I change the return type of each function to u8
rather than &[u8]
it compiles just fine:
pub struct Something {
value: usize,
}
impl Something {
pub fn get_and_increment(&mut self) -> u8 {
let res = self.get();
self.value += 1;
res
}
pub fn get(&self) -> u8 {
3
}
}
Why is it that Rust doesn't let me use the value
property of Something
in the get_and_increment
function after self.get
is called but only when both functions return &[u8]
?