Hacker News new | ask | show | jobs
by lynx23 590 days ago
I am not an active Zig guy, so... YYMV, but... To me, the examples are actually not self explanatory. What does the _ do? How are these constants used? Why is it something special? C had enums since forever, what is the novelty here?
1 comments

C has a rather weak type system: using one enum type in a function that takes a different enum isn't guaranteed to be an error, instead they promote to an integer type and silently convert (though you can set up most compilers to make this an error, e.g. `-Wenum-conversion` and `-Werror` for GCC & Clang).

The basic idea is the "newtype" pattern: different types may have exactly the same valid set of values, but not be interchangeable.

E.g. kilograms and US customary pounds, or meters and miles. If you've got a function `f(distance: double)` where `distance` needs to be in kilometers but your program also handles miles, it's nice to be able to define a type for kilometers that's different from the type for miles so the function won't compile if passed in miles incorrectly. So you get `f(distance: kilometers)`. That also stops someone passing in pounds to `f`, or any other such nonsense.