Skip to content

Incorrect error when using mem::size_of with generics, and "const_size_of" feature enabled.  #50651

Closed
@peterjoel

Description

@peterjoel

See playground.

I have a function like this:

fn make_empty_array_gen<T>() -> T {
    unsafe {
        let tmp = [0u8; mem::size_of::<T>()];
        mem::transmute(tmp)
    }
}
fn main() {
    let mut foo_gen: [u64; 5] = make_empty_array_gen();
    println!("foo_gen = {:?}", foo_gen);
}

Which, in this usage, I'd expect to be monomorphised like this:

fn make_empty_array() -> [u64; 5] {
    unsafe {
        let tmp = [0u8; mem::size_of::<[u64; 5]>()];
        mem::transmute(tmp)
    }
}

Which has no problems if I just write it like that instead of using generics. But the generic version gives this error:

error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
  --> src/main.rs:14:25
   |
14 |         let tmp = [0u8; mem::size_of::<T>()];
   |                         ^^^^^^^^^^^^^^^^^ `T` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `T`
   = help: consider adding a `where T: std::marker::Sized` bound
   = note: required by `std::mem::size_of`

I'm not sure if this use case is intended to be supported. But, even if it isn't, the error message is very bad, since T: Sized should always be an implied constraint here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions