• fruitcantfly@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    2 hours ago

    The problem of enums in other languages is that they do not make for a distinct type. They are just integers in a name. Or at least that is the case for C and Java enums. Python and JavaScript do not even have enums, which is even worse.

    Strongly typed enums is hardly unique to Rust.

    C++ has had them for a long time, for example: Using a plain integer type where an enum is expected has been prohibited since at least C++98. You can still use an enum in the place of an int, unless you use scoped enums (C++11 or later), which also require an explicit cast to convert from enum to the underlying type.

    And Python has had some form of enum since since 3.4: https://docs.python.org/3/library/enum.html. It’s not a language level feature, but that probably wouldn’t make much of a difference, and it’s as type safe as anything else in the language. But you will get a error when using type-hints, if you pass the wrong type to a function expecting an enum:

    from enum import Enum
    
    class MyEnum(Enum):
        A = 1
        B = 2
    
    def foo(_: MyEnum): ...
    
    foo(1)  # error: Argument 1 to "foo" has incompatible type "int"; expected "MyEnum"  [arg-type]