Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using while let with two variables simultaneously

I'm learning Rust and have been going through leetcode problems. One of them includes merging two linked lists, whose nodes are optional. I want to write a while loop that would go on until at least 1 node becomes None, and I was trying to use the while let loop for that.

However, it looks like the while let syntax supports only one optional, e.g.:

while let Some(n) = node {
   // do stuff
}

but I can't write

while let Some(n1) = node1 && Some(n2) = node2 {
}

Am I misunderstanding the syntax? I know I can rewrite it with a while true loop, but is there a more elegant way of doing it?

Also, can one do multiple checks with if let? Like if let None=node1 && None=node2 {return}

like image 740
Ibolit Avatar asked Oct 12 '25 03:10

Ibolit


1 Answers

You can pattern match with Option::zip:

while let Some((n1, n2)) = node1.zip(node2) {
    ...
}
like image 108
Netwave Avatar answered Oct 14 '25 20:10

Netwave