我正在尝试这样做,但不起作用:
fn foo() {
let v = b"Hello".to_vec();
let a = v.as_bytes();
}
Run Code Online (Sandbox Code Playgroud)
我越来越:
error[E0599]: no method named `as_bytes` found for struct `Vec<u8>` in the current scope
--> foo
|
26 | let a = v.as_bytes();
| ^^^^^^^^ method not found in `Vec<u8>`
Run Code Online (Sandbox Code Playgroud)
在 Rust 中,数组的长度以其类型 \xe2\x80\x93 进行编码,例如[u8; 5]\xe2\x80\x93 它是编译时属性,而Vec\ 的长度是运行时属性。每个字节数组 都[u8; N]实现TryFrom<Vec<u8>>,因此Vec<u8>实现TryInto<[u8; N]>作为结果。因此,您可以try_into()在Vec<u8>将其转换为字节数组:
let a: [u8; 5] = v.try_into().unwrap();\nRun Code Online (Sandbox Code Playgroud)\n请注意,TryInto::try_into()返回 a 的Result原因如上所述:a 的长度属性的性质Vec与数组 \xe2\x80\x93 分别在运行时和编译时不匹配。
为什么不将其转换Vec<u8>为字节切片呢?
请记住,您可以轻松地&[u8]从Vec<T>. derefVec<u8> 强制执行:[u8]Deref<Target=[u8]>
let v = b"Hello".to_vec();\nlet a: &[u8] = &v;\nRun Code Online (Sandbox Code Playgroud)\n您还可以as_slice()致电Vec<u8>:
let a = v.as_slice();\nRun Code Online (Sandbox Code Playgroud)\n这可能是您想要的,因为您可能正在使用 aVec来在运行时更改长度。