Change values via mutable reference

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 = 
      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?

In your code, what is ref_list?

Also, you don't appear to be initializing it with random numbers, just one random number.

It might help people help you if you present that as a complete minimal program, inc. main() and all data declarations.

Also every answer to questions about linked lists in Rust has to include the question: Have you read this: ?


My bad, it is actually iter_list. I forgot to refactor them all.

BTW just ignore the random number thing since that is not important at all/

Wow that's a very nice doc! I will check it right away. Thx.