4 ms·
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
by bryanrasmussen 6y ago
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.
- vpzom 6y agoNo, if expressions can basically only be used with else, otherwise you have a type mismatch
- conradludgate 6y agoIt wouldn't work like that but if you made them else if and else branches respectively then yes it would. Each if/if else/else block as a whole is a single statement. But two if statements and a literal is three individual statements
- TheDong 6y agoIf 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!