Is there any `if let x and y` syntax in rust?

It seems the following syntax is not supported in rust, i am just wondering if there is any alternative

if let Some((a1, b1)) = left.split_once("-") && Some((a2, b2)) = right.split_once("-") {
  // do something
}

let-chains is exactly what you want, but it's still unstable, and hopefully will be stable soon. Meanwhile in this specific case, you can use Option::zip.

2 Likes
if let (Some((a1, b1)), Some((a2, b2)) = (left.split_once("-"), right.split_once("-")) {
    // do something
}
4 Likes

The let_chains feature (which is still unstable right now, but can be used in the nightly compiler with #![feature(let_chains)]) allows you to do:

if let Some((a1, b1)) = left.split_once("-") && let Some((a2, b2)) = right.split_once("-") {
  // do something
}

Notice the let before the second Some.

The feauture was supposed to be stabilized a couple of months ago but some problems were found and it was postponed. Hopefully it will become stable soon enough.

Another alternative to not introduce too much indentation levels nor really big patterns would be to use the let-else and break-label features:

'scope: {
    let Some((a1, b1)) = left.split_once("-") else { break 'scope };
    let Some((a2, b2)) = right.split_once("-") else { break 'scope };
    // do something
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.