Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The size for values of type `T` cannot be known at compilation time when using mem::size_of::<T> as an array length

Tags:

generics

rust

Consider the following function:

fn make_array<T>()
where
    T: Sized,
{
    let bytes = [0u8; std::mem::size_of::<T>()];
}

For whatever reason it fails to compile

error[E0277]: the size for values of type `T` cannot be known at compilation time
 --> src/lib.rs:5:23
  |
5 |     let bytes = [0u8; std::mem::size_of::<T>()];
  |                       ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `T`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = help: consider adding a `where T: std::marker::Sized` bound
  = note: required by `std::mem::size_of`

This is despite the fact that there is a Sized trait bound for the generic parameter T. It doesn't make any sense to me.

Why is this happening and how do I work around it?

like image 709
0x400921FB54442D18 Avatar asked Jun 21 '19 14:06

0x400921FB54442D18


1 Answers

It seems to be bug #43408: Array lengths don't support generic parameters.

like image 178
michalsrb Avatar answered Nov 07 '22 13:11

michalsrb