logoalt Hacker News

tialaramexyesterday at 6:25 PM2 repliesview on HN

The C and Rust union types are extremely sharp blades, enough so that I expect the average Rust beginner doesn't even know Rust has unions (and I assume you were thinking of Rust's enum not union)

I've seen exactly one Rust type which is actually a union, and it's a pretty good justification for the existence of this feature, but one isn't really enough. That type is MaybeUninit<T> which is a union of a T and the empty tuple. Very, very, clever and valuable, but I didn't run into any similarly good uses outside that.


Replies

amlutoyesterday at 8:16 PM

> The C and Rust union types are extremely sharp blades

Sure, but the comparable Rust feature is enum, not union.

masklinnyesterday at 6:37 PM

Unions can be used as a somewhat safer (not safe by any means but safer), more flexible, and less error-prone form of transmute. Notably you can use unions to transmute between a large type and a smaller type.

That is essentially the motivation, primarily in the context of FFI where matching C's union behaviour using transmute is tricky and error-prone.

show 1 reply