Remix.run Logo
kace91 a day ago

I like rust matching for this reason: You need to cover all branches.

In fact, not using a default (the else clause equivalent) is ideal if you can explicitly cover all cases, because then if the possibilities expand (say a new value in an enum) you’ll be annoyed by the compiler to cover the new case, which might otherwise slip by.

uecker 15 hours ago | parent [-]

And I like using enums in C ;-) The compiler tells you to cover all branches.

https://godbolt.org/z/bY1P9Kx7n

kace91 11 hours ago | parent | next [-]

Rust is a bit smarter than that, in that it covers exhaustiveness of possible states, for more than just enums:

fn g(x: u8) { match x { 0..=10 => {}, 20..=200 => {},

    }
}

That for example would complain about the ranges 11 to 19 and 201 to 255 not being covered.

You could try to map ranges to enum values, but then nobody would guarantee that you covered the whole range while mapping to enums so you’d be moving the problem to a different location.

Rust approach is not flawless, larger data types like i32 or floats can’t check full coverage (I suppose for performance reasons) but still quite useful.

uecker 11 hours ago | parent [-]

In principle C compilers can do this too https://godbolt.org/z/Ev4berx8d although you need to trick them to do this for you. This could certainly be improved.

rundev 12 hours ago | parent | prev [-]

The compiler also tells you that even if you cover all enum members, you still need a `default` to cover everything, because C enums allow non-member values.