这段代码并没有太多意义,因为无论是否使用if let
,它都会返回同样的结果,但它是我遇到的问题的一个简洁例子:
struct Data {
value: Option<i32>,
}
impl Data {
fn get(&mut self) -> Option<&mut i32> {
if let Some(val) = &mut self.value {
return Some(val);
}
return self.value.as_mut();
}
}
这段代码产生了错误:
error[E0499]: cannot borrow `self.value` as mutable more than once at a time
--> src/lib.rs:11:16
|
6 | fn get(&mut self) -> Option<&mut i32> {
| - let's call the lifetime of this reference `'1`
7 | if let Some(val) = &mut self.value {
| --------------- first mutable borrow occurs here
8 | return Some(val);
| --------- returning this value requires that `self.value` is borrowed for `'1`
...
11 | return self.value.as_mut();
| ^^^^^^^^^^ second mutable borrow occurs here
我不明白为什么这是第二个可变借用,因为第一个在第二个发生之前就已经超出其作用域了。
在if let
之后,变量val
不在作用域中,那么它怎么会是第二个借用呢?第一个借用应该已经被释放了。
为了确保,我甚至将if let
包裹在另一个块中:
{
if let Some(val) = &mut self.value {
return Some(val);
}
}
return self.value.as_mut();
这导致了相同的错误。这里发生了什么?
return
不是惯用语。 - Shepmaster