you are viewing a single comment's thread
view the rest of the comments
[–] [S] 12 points 1 day ago (4 children)

Another comment on this post have declared enums outside of Rust being bad for not having tagged union capabilities.

  • source
  • parent
  • hideshow 4 child comments
  • [–] 1 point 9 hours ago (1 child)

    That's just someone that doesn't know why people say things, so just made it up.

    Enums outside of rust are indeed bad (I would correct it to enums in every language I know that is not rust, since maybe some other do the same thing as rust). But it's not because the tagged union thing.

    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.

    When enums are just integers, you don't know if a variable of the type of the enum is actually one of the variants of the enum. If you assume that, you can easily get into undefined behavior/crash territory quite fast.

    When making a library in C, for example, if one of your functions has an enum as a parameter, one of the first things you have to do is check if that parameter is actually in the range of the enum. Since you don't control the caller to your function. These checks don't belong in code at runtime, they belong to compile time, as you're just validating the type of a variable.

    In rust, switch/match statements need to cover every single enum variant (of course, you can also have default paths to not cover every case) your code just won't compile if you don't. Which means that when you add a new variant to an old enum, you don't have to go hunting every match statement to see if it affects your new change. That is a tedious and error-prone task if done manually, while it is pretty simple for the compiler.

    Of course, now that these differences are established, the tagged union thing comes in and makes rust ones better. The reason other language enums are bad is because they're named integers, the reason rust's are good is because they are tagged unions, completing the algebraic type system.

  • source
  • parent
  • hideshow 1 child comment
  • [–] 3 points 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.

    This is not the case for Java enums.

  • source
  • parent