我有以下代码
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 不允许我在 self 之后的
被调用但仅当两个函数都返回 get_and_increment
函数中使用 Something
的 value
属性。 get&[u8]
?
最佳答案
我强烈建议返回并重新阅读 The Rust Programming Language ,特别是关于references and borrowing的章节.
Why does returning a &[u8] rather than u8 from a function in Rust borrow self?
你本质上在问
why does returning «something that is borrowed» rather than «something that is not borrowed» from a function «require a borrow»?
遗憾的回答是:因为u8
不是借来的,而&[u8]
是借来的。
Why is it that Rust doesn't let me use the
value
property
因为在检查 get_and_increment
的主体时,编译器不知道 self
的哪些值作为 get
的一部分返回。您的 get
实现完全有可能返回对 value
的引用,或者将来可能,因此编译器必须采取保守的方式路由并禁止它。
but only when both functions return
&[u8]
?
这是不准确的。 get_and_increment
的返回类型对错误没有影响。 get
的返回类型仅在它包含引用时才重要。
然而,您没有明显的理由返回引用:
pub fn get(&self) -> [u8; 2] {
[3; 2]
}
如果你出于某种原因想要返回一个引用,它不需要绑定(bind)到 self
的生命周期(你的代码因为 lifetime elision ):
pub fn get(&self) -> &'static [u8] {
&[3; 2]
}
另见:
关于rust - 为什么从 Rust 中的函数返回一个 &[u8] 而不是 u8 借用自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777187/