Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining else clauses in nested if statements in Rust

Tags:

rust

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?

like image 670
yinnonsanders Avatar asked Oct 17 '25 08:10

yinnonsanders


2 Answers

You can use a closure

let z = (|| {
    if condition1 {
        do_something();
        if condition2 {
            return x;
        }
    };
    y 
})();
like image 52
red75prime Avatar answered Oct 18 '25 22:10

red75prime


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.

like image 41
mcarton Avatar answered Oct 18 '25 23:10

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!