Is still require nested if
if let Some(pos) = pos {
if pos > 0 {
do_something(pos);
}
}
or match
match pos {
Some(pos) if pos > 0 => {
do_something(pos);
}
_ => {}
}
?
May be there is some feature, may be nightly only
that allow to write:
if let Some(pos) = pos && pos > 0 {
do_something(pos);
}
?
error[E0658]: `let` expressions in this position are unstable
--> src/main.rs:3:8
|
3 | if let Some(pos) = pos && pos > 0 {
| ^^^^^^^^^^^^^^^^^^^
|
= note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information
= help: add `#![feature(let_chains)]` to the crate attributes to enable
2 Likes
kpreid
April 13, 2022, 8:58pm
4
Here is a way to get the same effect in current stable Rust:
if let Some(pos) = pos.filter(|&p| p > 0) {
do_something(pos);
}
3 Likes
but your match
example works as expected?
You can do that specific condition (while reusing the matched contents) with ident @ 1..
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0ad6de773454199d071a5f066a0b6806
fn main(){
for opt in [Some(0), Some(1), Some(2), None] {
if let Some(x @ 1..) = opt {
println!("matches, x: {x} opt: {opt:?}");
} else {
println!("doesn't match, opt: {opt:?}");
}
}
}
this prints
doesn't match, opt: Some(0)
matches, x: 1 opt: Some(1)
matches, x: 2 opt: Some(2)
doesn't match, opt: None
8 Likes
system
Closed
July 12, 2022, 10:04pm
7
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.