2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
minutes: 5
|
|
|
|
---
|
|
|
|
|
2022-12-21 16:36:30 +01:00
|
|
|
# Unions
|
|
|
|
|
|
|
|
Unions are like enums, but you need to track the active field yourself:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
#[repr(C)]
|
|
|
|
union MyUnion {
|
|
|
|
i: u8,
|
|
|
|
b: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let u = MyUnion { i: 42 };
|
|
|
|
println!("int: {}", unsafe { u.i });
|
2023-12-31 00:15:07 +01:00
|
|
|
println!("bool: {}", unsafe { u.b }); // Undefined behavior!
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|
2023-01-17 16:35:54 +00:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
Unions are very rarely needed in Rust as you can usually use an enum. They are
|
|
|
|
occasionally needed for interacting with C library APIs.
|
2023-01-17 16:35:54 +00:00
|
|
|
|
|
|
|
If you just want to reinterpret bytes as a different type, you probably want
|
2023-12-31 00:15:07 +01:00
|
|
|
[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html)
|
|
|
|
or a safe wrapper such as the [`zerocopy`](https://crates.io/crates/zerocopy)
|
|
|
|
crate.
|
2023-01-17 16:35:54 +00:00
|
|
|
|
|
|
|
</details>
|