Reputation: 9720
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}
Upvotes: 4
Views: 1359
Reputation: 70830
In addition to what @Netwave said, on nightly you can use the unstable let_chains
feature:
#![feature(let_chains)]
while let Some(n1) = node1 && let Some(n2) = node2 {
// ...
}
Upvotes: 8
Reputation: 42678
You can pattern match with Option::zip
:
while let Some((n1, n2)) = node1.zip(node2) {
...
}
Upvotes: 11