Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...