I had an RFC before for unsafe enums: https://github.com/rust-lang/rfcs/pull/724
Unfortunately it was closed and postponed, but now that we’ve gone through several stable versions of Rust, maybe it is time to reconsider it, especially since there still isn’t any sort of nice way to deal with C unions in Rust for FFI purposes. Also because the latest core team meeting expressed an interest in finally paying attention to people trying to do FFI from Rust. Here are the options:
- Unsafe enums with pattern destructuring
- Unsafe enums with direct field access
- Repr union structs with direct field access
- I think people who use unions deserve to suffer with their terrible macro solutions
0 voters
Unsafe enums with pattern destructuring:
unsafe enum MyUnion { Foo(i32), Bar { x: i32, y: f32 } }
let thing = MyUnion::Foo(5);
let x = unsafe { let MyUnion::Foo(x) = thing; x }
Unsafe enums with direct field access:
unsafe enum MyUnion { Foo(i32), Bar { x: i32, y: f32 } }
let thing = MyUnion::Foo(5);
let x = unsafe { thing.Foo.0 };
Repr union structs with direct field access:
#[repr(union)] struct MyUnion { foo: i32, bar: (i32, f32) }
let thing = MyUnion { foo: 5 };
let x = unsafe { thing.foo };
Keep in mind that if we do go with the unsafe enums approach, both pattern destructuring and direct field access can coexist.
So, let’s get this thing rolling again and try to finally support unions properly.