-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Labels
A-arrayArea: `[T; N]`Area: `[T; N]`A-const-genericsArea: const generics (parameters and arguments)Area: const generics (parameters and arguments)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language teamRelevant to the language team
Description
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
Kixunil, brendanzab, timvermeulen, luojia65, jonhoo and 51 moreschneiderfelipe
Metadata
Metadata
Assignees
Labels
A-arrayArea: `[T; N]`Area: `[T; N]`A-const-genericsArea: const generics (parameters and arguments)Area: const generics (parameters and arguments)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language teamRelevant to the language team