Skip to content

Unsafe block is overlooked #61365

Closed
Closed
@DutchGhost

Description

@DutchGhost

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions