Hacker News new | past | comments | ask | show | jobs | submit login

Don’t forget rust also has unions. Not using the name “union” for a feature that’s different than unions doesn’t feel “obviously wrong” to me.



Rust's Union is for C FFI, right?

Why not call Enum Union, and the FFI one CUnion or something? Like, is there something meaningful that Union is for other than C interop? Isn't it functionally identical to a tagged union in every other respect?


C FFI is a very useful thing, sure, but I don’t think it’s exclusive to that. It’s a nice primitive to have access to. I think Rust would feel weird with tagged unions and not untagged ones, just like having both sum and product types are good.


> Rust's Union is for C FFI, right?

No :)

> is there something meaningful that Union is for other than C interop?

Look more closely at the Rust standard library, MaybeUninit<T> is a union.


The right solution was to make union safe with an opt-in way to make it unsafe IMO.


The thing is that accessing an untagged union's data is just inherently unsafe. Say you made a union with a `u8` field and a `bool` field. If you had an instance of it and set its value to `5`, that's just not a valid `bool`. Hence the requirement of `unsafe`; you need to tell the compiler that you _know_ it's a valid value at the point you're accessing it.


Then make them tagged, that's what rust enums are, tagged unions, except they're called enums instead of unions.


I mean... yeah, that's exactly why Rust has tagged unions as well... both are useful in the right contexts, but tagged unions are easier to work with in general. That doesn't mean that (untagged) unions should be safe to work with though, because they can't be.


In concrete terms, what would that look like?


Syntax wise Zig does it with union(enum). Union and Enums are both concepts directly related to C and can be used separately too.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: