这个问题在这里已经有了答案:
The size for values of type `T` cannot be known at compilation time when using mem::size_of::<T> as an array length
(1 个回答)
去年关闭。
我要转换 T
到字节数组,
fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
unimplemented!()
}
当我调用这个函数时let a = to_bytes::<u32>();
类型将被确认,但出现错误:error[E0277]: the size for values of type `T` cannot be known at compilation time
--> lab/test-bit/src/main.rs:3:56
|
3 | fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
| - this type parameter needs to be `Sized` ^ doesn't have a size known at compile-time
|
最佳答案
稳定版 Rust 不支持在 const 表达式中使用泛型参数。
在 nightly 中,只要启用 const_generics
,代码应该可以工作。和 const_evaluatable_checked
.
在任何情况下,您都不需要 Sized
绑定(bind),是隐含的。
关于Rust:如何在编译时或其他方式获取 sizeof::<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65638902/