【发布时间】:2017-02-28 02:23:27
【问题描述】:
我有一个未知大小的字节缓冲区,我想创建一个指向缓冲区开头内存的局部结构变量。按照我在 C 中所做的,我在 Rust 中尝试了很多不同的东西,并且不断出错。这是我最近的尝试:
use std::mem::{size_of, transmute};
#[repr(C, packed)]
struct MyStruct {
foo: u16,
bar: u8,
}
fn main() {
let v: Vec<u8> = vec![1, 2, 3];
let buffer = v.as_slice();
let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
}
我收到一个错误:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> src/main.rs:12:42
|
12 | let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `[u8]`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
【问题讨论】:
-
您将无法执行此操作,因为需要
transmute在编译时知道大小。您使用*mut指针的解决方案看起来就像您必须这样做
标签: data-structures rust