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

How to have multiple `let Some()` in a single line where the second `let` is dependent on the first?

Is something like this possible where both let Some(...) are in the same line and the second let is dependent on the first let?

let Some(h) = socket.req_parts().headers.get("room"), let Some(room) = h.to_str() else {
    return;
};

This solution:

How to write multiple condition in if let statement?

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

proposes using tuples but I am not sure how to do that when second let is dependant on first.

>Solution :

You’re right, you can’t do two separate dependent let Some()s at the same time, when the dependency is through a function call. In your link comments show examples of "dependent" matches with @ identifiers:

if let Some(c @ Some(7)) = a

This works because it’s in a sense equivalent to

if let Some(Some(7)) = a

with the addition of binding the Some(7) to c. The dependency is expressed on the left-hand-side, in the pattern. You can’t put your function call there.

Since you want to go into the else clause if either h or room would be None, you can instead use Option.and_then, which takes a function returning an Option as its argument, and only applies it to Some. This is cleanest if you just need room:

let Some(room) = socket.req_parts().headers.get("room").and_then(|h| h.to_str())

But you could also use tuples to get both room and h:

let Some((h, room)) = socket.req_parts().headers.get("room").and_then(|h| (h, h.to_str()))
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