3 ms·
If you wanted to list out cases without having to use `if`, `else if`, you'd idiomatically use match: fn calculate_tax(income: i32) -> i32 { match
by TheDong 6y ago
If you wanted to list out cases without having to use `if`, `else if`, you'd idiomatically use match:
fn calculate_tax(income: i32) -> i32 {
match income {
0..10 => 0,
10..50 => 20,
_ => 50,
}
}
See this playground for a couple other alternatives using match too https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=1e7b3da5d8821ee99ee6d7f6936b0e21 https://play.rust-lang.org/?version=nightly&mode=debug&editi...
As others explained, you do need a default case (either an 'else' in your if statement, or an exhaustive match), otherwise how would the expression typecheck?
For a concrete example, if you use an 'if' only, you can have the following:
let x = if income < 10 { 0 };
At that point, there's no way to statically know x's type. If income is >= 10, x is what?
In order to convince the compiler x has a statically knowable type, the "if" expression need an else statement, or should be converted into a match that the compiler can prove is exhaustive.
- bad-apple 6y agoNitpick: I'm pretty sure that "11..50" should be a "10..50".
- TheDong 6y agoEdited, yeah. Off-by-one errors, can't live without em.
- bad-apple 6y agoIf you'd used 50.. instead of _, Rust would've caught this error for you. ;) https://play.rust-lang.org/?version=nightly&mode=release&edition=2018&gist=1e2c0564b7e4ed887cd89c557898f3c2 https://play.rust-lang.org/?version=nightly&mode=release&edi...
- bryanrasmussen 6y agoThanks!