I'm trying to create a generic function that transmutes a slice of bytes into an integer.
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 won't let me do that:
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`
Is there a way that I can statically know the size of T?