Can't read &[MyType(u8)] from &[u8] with Zerocopy
⚓ Rust 📅 2025-10-30 👤 surdeus 👁️ 4I'm trying to write a Vec of my u8 wrapper type into bytes and then use ref_from_bytes/prefix/suffix, but it won't compile.
I had the compiler demand KnownLayout for another struct, but adding a derive macro there worked and fixed it. Here instead, it won't.
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
#[derive(Clone, Debug, FromBytes, IntoBytes, Immutable, KnownLayout)]
pub struct Cost(pub u8);
fn main() {
let costs = vec![Cost(10), Cost(20), Cost(30), Cost(40), Cost(50), Cost(60), Cost(70), Cost(80), Cost(90), Cost(100)];
let mut data: Vec<u8> = vec![]; // vec![0; 16];
println!("data before: {:?}", data);
costs.write_to_io(&mut data).unwrap();
println!("data after: {:?}", data);
let (c2, data3) = Cost::ref_from_prefix_with_elems(&data, 10).unwrap();
}
The error:
error[E0271]: type mismatch resolving `<Cost as KnownLayout>::PointerMetadata == usize`
--> src/main.rs:37:20
|
37 | let (c2, data3) = Cost::ref_from_prefix_with_elems(&data, 10).unwrap();
| ^^^^ type mismatch resolving `<Cost as KnownLayout>::PointerMetadata == usize`
|
note: expected this to be `usize`
--> src/main.rs:6:57
|
6 | #[derive(Clone, Debug, FromBytes, IntoBytes, Immutable, KnownLayout)]
| ^^^^^^^^^^^
note: required by a bound in `ref_from_prefix_with_elems`
--> /home/culebron/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/zerocopy-0.8.27/src/lib.rs:4190:27
|
4185 | fn ref_from_prefix_with_elems(
| -------------------------- required by a bound in this associated function
...
4190 | Self: KnownLayout<PointerMetadata = usize> + Immutable,
| ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `FromBytes::ref_from_prefix_with_elems`
= note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info)
2 posts - 2 participants
🏷️ Rust_feed