Is there an idiomatic way in Rust to do the following:
let z =
if (condition1) {
do_something();
if (condition2) {
x
} else {
y
}
} else {
y
}
Alternatively:
let z =
if (condition1 && condition2) {
do_something();
x
} else if (condition1) {
do_something();
y
} else {
y
}
Of course, if this was a fully imperative language (and this was in a function), I could combine the two else
clauses:
if (condition1) {
do_something();
if (condition2) {
return x;
}
}
return y;
But I cannot use:
let z =
{
if (condition1) {
do_something();
if (condition2) {
return x;
}
}
return y;
}
But since both the inner and the outer if statement (for the first example) must evaluate to an object of whatever type T
is and cannot evaluate to ()
, that doesn't seem possible to use in all cases, for example, when you are defining a variable by the evaluation of the if-statement. Is there a better way?
You can use a closure
let z = (|| {
if condition1 {
do_something();
if condition2 {
return x;
}
};
y
})();
You could use a loop
with a break
value:
let z = loop {
if condition1 {
do_something();
if condition2 {
break x;
}
}
break y;
};
There is an RFC open now about allowing regular blocks to do that to avoid this kind of never looping loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With