我有以下代码
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]
}
}
当我尝试编译这个时,我得到这个错误:
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
如果我将每个函数的返回类型更改为u8
而不是&[u8]
编译就好了:
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
}
}
为什么 Rust 不允许我在调用后使用函数中的value
属性,但只有在两个函数都返回时才使用?Something
get_and_increment
self.get
&[u8]