Strange borrowing error when working with linked lists

⚓ Rust    📅 2025-11-03    👤 surdeus    👁️ 6      

surdeus

I have a strange borrowing error and don't understand why it happens. Maybe someone can help:

struct Node {
    next: Option<Box<Node>>,
}

fn append(mut root: &mut Node, value: Node) {
    while let Some(last) = &mut root.next {
        root = last;
    }
    root.next = Some(Box::new(value));
}

Produces error:

5 | fn append(mut root: &mut Node, value: Node) {
  |                     - let's call the lifetime of this reference `'1`
6 |     while let Some(last) = &mut root.next {
  |                            -------------- `root.next` is borrowed here
7 |         root = last;
  |         ----------- assignment requires that `root.next` is borrowed for `'1`
8 |     }
9 |     root.next = Some(Box::new(value));
  |     ^^^^^^^^^ `root.next` is assigned to here but it was already borrowed

But why? Souldn't lifetime of all the nodes be the same in this case?
One strange thing is that changing it to Some(mut ref last) fixes the problem.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed