我遇到了一个混乱的错误,关于同时使用可变和不可变借用,在我期望可变借用结束后。我已经对类似问题进行了大量研究(1, 2, 3, 4, 5),这使我相信我的问题与词法生命周期有关(尽管打开NLL功能并在夜间编译时不会改变结果),但我不知道具体是什么;我的情况似乎不符合其他问题的任何情况。
pub enum Chain<'a> {
Root {
value: String,
},
Child {
parent: &'a mut Chain<'a>,
},
}
impl Chain<'_> {
pub fn get(&self) -> &String {
match self {
Chain::Root { ref value } => value,
Chain::Child { ref parent } => parent.get(),
}
}
pub fn get_mut(&mut self) -> &mut String {
match self {
Chain::Root { ref mut value } => value,
Chain::Child { ref mut parent } => parent.get_mut(),
}
}
}
#[test]
fn test() {
let mut root = Chain::Root { value: "foo".to_string() };
{
let mut child = Chain::Child { parent: &mut root };
*child.get_mut() = "bar".to_string();
} // I expect child's borrow to go out of scope here
assert_eq!("bar".to_string(), *root.get());
}
出现的错误是:
error[E0502]: cannot borrow `root` as immutable because it is also borrowed as mutable
--> example.rs:36:36
|
31 | let mut child = Chain::Child { parent: &mut root };
| --------- mutable borrow occurs here
...
36 | assert_eq!("bar".to_string(), *root.get());
| ^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
我理解为什么会有一个不可变借用,但我不明白如何在那里使用可变借用。两者如何同时使用?希望有人能解释发生了什么以及如何避免。