Closed
Description
I know this code horribly wrong, and it doesnt compile. Even when I expect it to compile:
#![feature(const_fn_union)]
#![feature(const_generics)]
union Transmute {
example: Example,
num: usize,
}
#[derive(Copy, Clone)]
#[repr(C)]
enum Example {
field = 1,
}
const fn transpose(n: usize) -> Example {
unsafe {
Transmute { num: n }.example
}
}
fn main() {
}
It complains that we need an unsafe block:
error[E0133]: access to union field is unsafe and requires unsafe function or block
--> src/main.rs:17:9
|
17 | Transmute { num: n }.example
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ access to union field
|
= note: the field may not be properly initialized: using uninitialized data will cause undefined behavior
error: aborting due to previous error
but we wrapped it in an unsafe block!
Changing the function signature to const *unsafe* fn transpose(n: usize) -> Example
does compile, and then we can leave out the inner unsafe block.