我一直在解决一些 LeetCode 的问题,其中遇到了一个我无法解释的问题。
#[derive(Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
fn main() {
let mut list = Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode { val: 3, next: None })),
})),
}));
let mut tail = &mut list.as_mut().unwrap().next;
// This compiles fine
// while tail.is_some() {
// tail = &mut tail.as_mut().unwrap().next;
// }
// This compiles fine
// while let Some(ref mut node) = tail {
// tail = &mut node.next;
// }
// However this does not
while let Some(node) = tail.as_mut() {
tail = &mut node.next;
}
*tail = Some(Box::new(ListNode::new(4)));
println!("{:#?}", list);
}
这是错误信息:
error[E0506]: cannot assign to `*tail` because it is borrowed
--> src/main.rs:39:5
|
35 | while let Some(node) = tail.as_mut() {
| ---- borrow of `*tail` occurs here
...
39 | *tail = Some(Box::new(ListNode::new(4)));
| ^^^^^
| |
| assignment to borrowed `*tail` occurs here
| borrow later used here
为什么在
while let Some() = xxx
循环之后,tail
仍然被借用?