News for hackers. Stuff that matters.
Re:Rust for JavaScript Developers – Functions and Control Flow by TheDong on Monday July 06, 2020 @02:50AM (#23745347)
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&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.

Re:Rust for JavaScript Developers – Functions and Control Flow by bad-apple on Monday July 06, 2020 @03:29AM (#23745538)
Nitpick: I'm pretty sure that "11..50" should be a "10..50".
Re:Rust for JavaScript Developers – Functions and Control Flow by TheDong on Monday July 06, 2020 @03:38AM (#23745584)
Edited, yeah. Off-by-one errors, can't live without em.
Re:Rust for JavaScript Developers – Functions and Control Flow by bad-apple on Monday July 06, 2020 @04:04AM (#23745695)
If you'd used 50.. instead of _, Rust would've caught this error for you. ;)

https://play.rust-lang.org/?version=nightly&mode=release&edi...

Re:Rust for JavaScript Developers – Functions and Control Flow by bryanrasmussen on Monday July 06, 2020 @05:04AM (#23745975)
Thanks!