【发布时间】:2015-05-14 17:28:54
【问题描述】:
为什么下面代码中的调用self.f2() 会触发借用检查器? else 块不是在不同的范围内吗?这真是一个难题!
use std::str::Chars;
struct A;
impl A {
fn f2(&mut self) {}
fn f1(&mut self) -> Option<Chars> {
None
}
fn f3(&mut self) {
if let Some(x) = self.f1() {
} else {
self.f2()
}
}
}
fn main() {
let mut a = A;
}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:16:13
|
13 | if let Some(x) = self.f1() {
| ---- first mutable borrow occurs here
...
16 | self.f2()
| ^^^^ second mutable borrow occurs here
17 | }
| - first borrow ends here
自我借用的范围不是以self.f1() 调用开始和结束吗?一旦来自f1() 的调用返回f1() 就不再使用self,因此借用检查器对第二次借用应该没有任何问题。注意下面的代码也失败了...
// ...
if let Some(x) = self.f1() {
self.f2()
}
// ...
我认为在这里第二次借用应该没问题,因为f1 和f3 没有与f2 同时使用self。
【问题讨论】:
标签: rust