Rust:如何在编译时或其他方式获取 sizeof::<T>?

标签 rust sizeof

这个问题在这里已经有了答案:





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/

相关文章:

rust - 如何防止 TcpStream 阻塞读取?

c++ - 为什么 sizeof(Derived4) 是 8 字节?我觉得应该是5个字节

c - 为什么我的代码中的 realloc() 和 free() 会失败?

c++ - sizeof(array) 在此 strstr 重新实现中未给出预期值

c++ - 关于类成员函数指针的sizeof

c - 为什么数组大小为 1

multithreading - 使用 channel 在线程之间传递 Rust pnet 数据包

rust - 引用和变异id_tree Rust的问题

rust - 如何在 Rust 中实现静态缓存?

rust - 如何在用户不按 Enter 键的情况下获取键盘输入?