|
|
Log in / Subscribe / Register

switch

switch

Posted Sep 12, 2021 8:08 UTC (Sun) by tialaramex (subscriber, #21167)
In reply to: Cro: Maintain it With Zig by HelloWorld
Parent article: Cro: Maintain it With Zig

Still a language mis-feature :D

In Rust, match (the closest feature to switch) must be exhaustive, you may choose to either write a default case *or* cover every possible value but not both as that's an error, for the same reason matching '7' twice in some digit matching code would be an error.

If the library you're using knows they might want to add more values to the enumeration they can declare it to be #[non_exhaustive] which signals to the compiler that the former scenario (cover every case explicitly) isn't enough after all and you must always supply a default. This way when the next library upgrade adds another value your default match covers that. USFederalHoliday should likely be #[non_exhaustive] but you don't need a default case for CalendarMonth or DayOfWeek.

If they choose not to write #[non_exhaustive] but then they do add a value to the enumeration anyway this is a backwards incompatible change and your code won't compile until it's adjusted to cope with the new value.

As a result the desired effect of the MISRA rule is always in place in Rust, while the dangerous behaviour is not possible, a guideline is unnecessary.


to post comments

switch

Posted Sep 12, 2021 11:23 UTC (Sun) by HelloWorld (guest, #56129) [Link] (1 responses)

In safety critical applications, which after all typically run in some sort of embedded system, I don't think you even need something like #[non_exhaustive]. When a new enumerator is added, you really should take another look and not just hope that your old default clause still makes sense. Binary compatibility is not that much of an issue in embedded systems because you don't usually upgrade shared libraries independently.

Besides, this is purely a tooling problem. If MISRA wants to enforce exhaustiveness, they can do so. But apparently their tool vendors are just too lazy and they prefer forcing people to write dead code instead.

switch

Posted Sep 20, 2021 10:42 UTC (Mon) by tialaramex (subscriber, #21167) [Link]

Exhaustiveness in C is really hard because the enumerated type is just a funny way to spell an integer as explained in the other sub-thread.

Obviously rustc turns your simply enumerated type into an integer in the machine code too, but this happens in an IR after you can't touch it, so the only rule needed to avoid setting yourself on fire is "No unsafe code" ie write #![forbid(unsafe_code)] and you're done.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds