9951 explained code solutions for 126 technologies


rustHow to iterate linked list in Rust


Iterating a linked list in Rust is done using a loop and the .next() method. The loop will continue until the .next() method returns None.

let mut current = list.head;
while let Some(node) = current {
    println!("{}", node.data);
    current = node.next;
}

Code explanation

  • let mut current = list.head: Declares a mutable variable current and assigns it to the head of the list.
  • while let Some(node) = current: Begins a loop that will continue until current is None.
  • println!("{}", node.data): Prints the data of the current node.
  • current = node.next: Assigns current to the next node in the list.

Helpful links

Edit this code on GitHub