Skip to content

Const generics and transmute: cannot transmute between types of different sizes #62875

Closed
@bgourlie

Description

@bgourlie

The following code should compile, but it doesn't:

#![feature(const_generics)]

use std::{
    mem::{self, MaybeUninit},
    ptr,
};

fn main() {
}

pub struct Foo<const SIZE: usize> {
    messages: [Option<String>; SIZE],
}

impl<const SIZE: usize> Default for Foo<{SIZE}> {
    fn default() -> Self {
        let arr = {
            let mut arr: [MaybeUninit<Option<String>>; {SIZE}] =
                unsafe { MaybeUninit::uninit().assume_init() };

            for elem in &mut arr[..] {
                unsafe { ptr::write(elem.as_mut_ptr(), None) }
            }

            unsafe { mem::transmute::<_, [Option<String>; {SIZE}]>(arr) }
        };
        Foo {
            messages: arr,
        }
    }
}

The error produced is

error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
  --> src\main.rs:25:22
   |
25 |             unsafe { mem::transmute::<_, [Option<String>; {SIZE}]>(arr) }
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: source type: `[std::mem::MaybeUninit<std::option::Option<std::string::String>>; _]` (this type does not have a fixed size)
   = note: target type: `[std::option::Option<std::string::String>; _]` (this type does not have a fixed size)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)C-bugCategory: This is a bug.F-const_generics`#![feature(const_generics)]`T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions