I don't know Rust - but is it possible to write it like this?
fn calculate_tax(income: i32) -> i32 { if income < 10 { 0 } if income < 50 { 20 } 50 }
on edit: tried to fix formatting but didn't work.
fn calculate_tax(income: i32) -> i32 { if income < 10 { 0 } if income < 50 { 20 } 50 }
on edit: tried to fix formatting but didn't work.
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&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.
https://play.rust-lang.org/?version=nightly&mode=release&edi...