logoalt Hacker News

ueckerlast Monday at 9:49 AM2 repliesview on HN

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

https://godbolt.org/z/bY1P9Kx7n


Replies

kace91last Monday at 1:55 PM

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.

show 1 reply
rundevlast Monday at 12:52 PM

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.