使用mem :: size_of :: <T>作为数组长度时,在编译时无法知道类型T的值的大小

时间:2019-06-21 14:26:03

标签: generics rust

考虑以下功能:

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

无论出于何种原因无法编译

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`

尽管事实是通用参数Sized绑定了T特征。对我来说没有任何意义。

为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:3)

似乎是错误#43408:Array lengths don't support generic parameters