Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}

>Solution :

You can pattern match with Option::zip:

while let Some((n1, n2)) = node1.zip(node2) {
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading