I want to switch through many possible cases for x
and there's one case (here x == 0
) where I want to check the result of some additional code to determine what to do next. One possibility is to return early from the match.
I'd use break
to do this early-returning in C, but this isn't allowed in Rust. return
returns from the parent function (in this case main()
) and not from the match only (i.e. the println!
at the end isn't run!).
I could just negate the sub-condition (here y == 0
) and indent the whole lot of following code -- but I find this ugly and unreadable.
Putting the sub-condition into a match-guard is no option for me since it's simply too big.
Is this possible in Rust or is there a better alternative (except creating another subfunction or other work-arounds)?
Minimal example:
fn main() {
let x = 1;
match x {
1 => {
let y = 0;
/*
* do ev1l stuff to y that I don't want to put into the match-guard
* as it's simply too much.
*/
/* break early ... */
if y == 0 {break;} // > error: `break` outside of loop [E0268]
assert!(y != 0, "y was 0!");
/* do other stuff in here. */
}
_ => {}
}
println!("done matching");
}
I found Mixing matching, mutation, and moves in Rust — is it wrong?
match
embraces both imperative and functional styles of programming: you can continue usingbreak
statements, assignments, et cetera, rather than being forced to adopt an expression-oriented mindset.
else
block. Oh, OP disallowed that. Maybe a match guard? Oh, OP disallowed that. Make a function? Oh, OP disallowed that. – Monkeypotbreak
since imho it's the most "clean" way to solve this problem. Ofcourse if it's not possible I will refrain to one of the other options but imho these are "overkill" for what I want to do. – Salmi