To make things easier, let me define a Node
like this:
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
And I want to initialize this linked list using random numbers. Here is the code that does not work:
let mut l_list = None;
let mut iter_list = &mut l_list;
let x = get_random_number();
for _ in 0..x {
if iter_list .is_none() {
iter_list = &mut Some(Box::new(ListNode{val:x, next:None})); // ERROR!
} else {
iter_list.as_mut().unwrap().next =
Some(Box::new(ListNode{val:x,next:None}));
iter_list = &mut iter_list .as_mut().unwrap().next;
}
}
I am getting the following error:
error[E0716]: temporary value dropped while borrowed
Any idea to solve this w/o using pointers or a dummy node?