News for hackers. Stuff that matters.
Re:Why Rust helps even if you have to use a lot of `unsafe` by retrac on Wednesday August 02, 2023 @11:38AM (#36972374)
We do not use unions very often in C/C++ because they are not safe. You have to know how to interpret it; the compiler can't and won't save you if you read the memory as the wrong type. You usually keep a variable set to the type the union is, and check it at run time.

Some languages do that wrapping and checking for you, automatically. Everything from Ada (variant records) to Haskell has them. You cannot mishandle such objects by misinterpreting them as the wrong type; it's a compile-time error in those languages to do so.

Imagine you are parsing something. In my opinion, the most natural way to express this, is a function that takes an array of characters and returns an array of parsed objects or tokens, where each object may be of a different possible type. A sum type allows one type to represent all those possible sub-types, and it does so with safety, and very little overhead. Runtime checks for appropriate type, can often be optimized away by the compiler with dataflow analysis.

There are no comments on this comment yet.