Skip to content

Const generics: Generic array transmutes do not work #61956

Closed
@HadrienG2

Description

@HadrienG2

This trivial transmute should work:

#![feature(const_generics)]

fn silly_default<const N: usize>(arr: [u8; N]) -> [u8; N] {
    unsafe { core::mem::transmute::<_, _>(arr) }
}

Unfortunately, it refuses to build with the following error:

error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> src/lib.rs:4:14
  |
4 |     unsafe { core::mem::transmute::<_, _>(arr) }
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `[u8; _]` does not have a fixed size

This means that the array initialization example from the core::mem::MaybeUninit documentation currently cannot be generalized to arrays of arbitrary size, as transmutes from [MaybeUnit<T>; N] to [T; N] won't compile.

A horribly error-prone workaround for generic array transmute is:

// Using &mut as an assertion of unique "ownership"
let ptr = &mut arr as *mut _ as *mut [T; N];
let res = unsafe { ptr.read() };
core::mem::forget(arr);
res

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`A-const-genericsArea: const generics (parameters and arguments)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language 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