我正在尝试创建一个通用函数,将字节的一部分转换为整数。
fn i_from_slice<T>(slice: &[u8]) -> Option<T>
where
T: Sized,
{
match slice.len() {
std::mem::size_of::<T>() => {
let mut buf = [0; std::mem::size_of::<T>()];
buf.copy_from_slice(slice);
Some(unsafe { std::mem::transmute_copy(&buf) })
}
_ => None,
}
}
Rust不会让我那样做:
error[E0532]: expected tuple struct/variant, found function `std::mem::size_of`
--> src/lib.rs:6:9
|
6 | std::mem::size_of::<T>() => {
| ^^^^^^^^^^^^^^^^^^^^^^ not a tuple struct/variant
error[E0277]: the size for values of type `T` cannot be known at compilation time
--> src/lib.rs:7:31
|
7 | let mut buf = [0; 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`
有没有办法我可以静态知道
T
的大小? 最佳答案
如果T
是整数,则不需要任何不安全的代码,因为存在 from_ne_bytes
。
如果您绝对需要通用函数,则可以添加一个特征:
use std::convert::TryInto;
trait FromBytes: Sized {
fn from_ne_bytes_(bytes: &[u8]) -> Option<Self>;
}
impl FromBytes for i32 {
fn from_ne_bytes_(bytes: &[u8]) -> Option<Self> {
bytes.try_into().map(i32::from_ne_bytes).ok()
}
}
// Etc. for the other numeric types.
fn main() {
let i1: i32 = i_from_slice(&[1, 2, 3, 4]).unwrap();
let i2 = i32::from_ne_bytes_(&[1, 2, 3, 4]).unwrap();
assert_eq!(i1, i2);
}
// This `unsafe` usage is invalid, but copied from the original post
// to compare the result with my implementation.
fn i_from_slice<T>(slice: &[u8]) -> Option<T> {
if slice.len() == std::mem::size_of::<T>() {
Some(unsafe { std::mem::transmute_copy(&slice[0]) })
} else {
None
}
}
关于rust - 无法创建将 byte slice 转换为整数的通用函数,因为在编译时大小未知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58196136/