Remix.run Logo
▲ slopinthebag 3 hours ago

i dont understand what rust doesn't give you that zig does?

▲Jtsummers 3 hours ago | parent [-]

https://zig.guide/language-basics/unions/ - Seems like it's more similar to Ada's variant records: https://learn.adacore.com/courses/intro-to-ada/chapters/more...

Instead of just getting one type that includes the discriminant and records, Zig and Ada have a tag of some type whose value determines which variant is being used, and then the union (Zig) or record (Ada) is its own type.

▲slopinthebag 2 hours ago | parent | next [-]

why would you ever need them to be seperate?

▲Jtsummers an hour ago | parent | next [-]

To use the discriminant type on its own without carrying the baggage of the entire record and all its data, or to use the discriminant type across multiple records rather than creating some mega-record or manually synchronizing them. In Ada (again, don't know Zig but from the docs it's similar to what Ada is doing), adding a new value to the discriminant enum would cause a compile time error in all the variant records using it and all the case statements (match, but Ada's version), as long as they didn't have a catchall branch.

▲12_throw_away 2 hours ago | parent | prev [-]

Because sometimes you just want to talk about the types of variants without having to construct a value. But, you probably don't want to manually maintain a separate enum just for the discriminants. Nor do you want to manually maintain the mappings between the original enum and the discriminant-only enum.

I've had it come up when dealing with ASTs, although I don't recall the specifics. This is a problem that's certainly pretty easy to solve with macros. I'm pretty sure last time I ran into this I used `strum` [1] and its `EnumDiscriminants` macro to handle this.

[1] https://lib.rs/crates/strum

▲slopinthebag 2 hours ago | parent [-]

ahh ok ive run into this before, yes either strum or i assumed i was doing something non-optimal if i had to talk about types like this

▲knorker 2 hours ago | parent | prev [-]

I still don't get it. Is it like a Rust enum, but worse, because you can accidentally only detect the problem at runtime?