4 ms·
It's a reasonable question. Aside from the nice data encapsulation of enums (which make them more like unions), the answer is basically "they're enforced". Mos
by leoedin 3y ago
It's a reasonable question. Aside from the nice data encapsulation of enums (which make them more like unions), the answer is basically "they're enforced".
Most C libraries and system calls return integers not enums. Often the meaning of those integers is hard coded in a header somewhere. There's no guarantee that the number returned will be one of the values in the header.
When a library does return enums, there's no guarantee the value returned is actually in the enum. It could be anything.
When you pattern match an enum in C, you have no checks to make sure you catch all the cases, or don't drop a break;.
All of the above means that in C, you're relying on the programmer to cross check they haven't made a mistake. Rust does it all for you - if you match against an enum type, you have to handle all the cases. You can't return anything other than the type you said you would. It basically does all the work that the programmer has to do in C. And most importantly, it does it every time you recompile. Even if the first person to call a function in C is meticulous, the members in the enum might change later.
- uecker 3y agoYou could have similar warning in C compilers: https://godbolt.org/z/aj6TWsxK3 https://godbolt.org/z/aj6TWsxK3 I agree that Rust has more comprehensive guard railes, but except for pointer ownership and sharing where C is missing tools (although model checking tools can achieve this too), I think you could basically have everything else in C as well by building similar abstractions building on existing compiler warnings and maybe adding a couple of new ones. So while I like some ideas of Rust, I think in the discussions proponents often compare it to a worst-case C without old programming style and no static analysis applied and comparing to an ideal Rust with no use of unsafe (and also this binder rewrite uses unsafe).