I am a rust beginer and I meet a problem when I do a simple preorder traversal with rust:
impl Solution {
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut ans = Vec::new();
if let Some(root) = root {
let mut stk: Vec<Rc<RefCell<TreeNode>>> = vec![root];
while !stk.is_empty() {
if let Some(cur) = stk.pop() { // cur: Rc<RefCell<TreeNode>>
ans.push(cur.borrow().val);
if let Some(right) = cur.borrow_mut().right.take() { stk.push(right); }
if let Some(left) = cur.borrow_mut().left.take() { stk.push(left); }
}
}
/* the following code is wrong, why???
while !stk.is_empty() {
let mut cur = stk.pop().unwrap();
ans.push(cur.borrow().val);
if let Some(right) = cur.borrow_mut().right.take() { stk.push(right); }
if let Some(left) = cur.borrow_mut().left.take() { stk.push(left); }
Line 30: Char 37: error: `cur` does not live long enough (solution.rs)
|
27 | let mut cur = stk.pop().unwrap();
| ------- binding `cur` declared here
...
30 | if let Some(left) = cur.borrow_mut().left.take() { stk.push(left); }
| ^^^-------------
| |
| borrowed value does not live long enough
| a temporary with access to the borrow is created here ...
31 | }
| -
| |
| `cur` dropped here while still borrowed
| ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `RefMut<'_, tree_node::TreeNode>`
|
help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped
|
30 | if let Some(left) = cur.borrow_mut().left.take() { stk.push(left); };
| +
For more information about this error, try `rustc --explain E0597`.
error: could not compile `prog` (bin "prog") due to 1 previous error
}
*/
}
ans
}
}
It seem that if let Some(x) = y
has a huge difference with let x = y.unwrap()
.
Who can tell me why, thanks a lot!