0

I am trying to make a list struct and implement a method that adds 1 to the next node if the current node's value is greater or equal to ten.

I write this while loop and want to assign inner_this to next node in loop:

struct ListNode {
    val: i32,
    next: Option<Box<ListNode>>,
}

fn check_ten(this: &mut Option<Box<ListNode>>, f: &i32) {
    let mut inner_this = this;
    let mut flag = *f;
    while let Some(t) = inner_this {
        t.val += flag;
        if t.val >= 10 {
            t.val = t.val - 10;
            flag = 1;
        } else {
            flag = 0
        }
        let next = &mut t.next;
        inner_this = next;
    }
}

fn main() {}

I get this compiler error:

error[E0499]: cannot borrow `inner_this.0` as mutable more than once at a time
  --> ATN.rs:9:20
   |
9  |     while let Some(t) = inner_this {
   |                    ^ mutable borrow starts here in previous iteration of loop
...
20 | }
   | - mutable borrow ends here

error[E0506]: cannot assign to `inner_this` because it is borrowed
  --> ATN.rs:18:9
   |
9  |     while let Some(t) = inner_this {
   |                    - borrow of `inner_this` occurs here
...
18 |         inner_this = next;
   |         ^^^^^^^^^^^^^^^^^ assignment to borrowed `inner_this` occurs here

Is there a way to implement this requirement and assign inner_this again? Do I need to use loop instead of while?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ccQpein
  • 705
  • 7
  • 20
  • I believe your question is answered by the answers of [Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time](https://stackoverflow.com/q/37986640/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster May 28 '18 at 16:45
  • 1
    TL;DR the duplicate: `while let Some(t) = { inner_this } {` – Shepmaster May 28 '18 at 16:46

0 Answers0