如何在 Rust 中将字节向量转换为字节数组?

yeg*_*256 3 rust

我正在尝试这样做,但不起作用:

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)

眠りネ*_*ネロク 5

在 Rust 中,数组的长度以其类型 \xe2\x80\x93 进行编码,例如[u8; 5]\xe2\x80\x93 它是编译时属性,而Vec\ 的长度是运行时属性。每个字节数组 都[u8; N]实现TryFrom<Vec<u8>>,因此Vec<u8>实现TryInto<[u8; N]>作为结果。因此,您可以try_into()Vec<u8>将其转换为字节数组:

\n
let a: [u8; 5] = v.try_into().unwrap();\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,TryInto::try_into()返回 a 的Result原因如上所述:a 的长度属性的性质Vec与数组 \xe2\x80\x93 分别在运行时和编译时不匹配。

\n
\n

为什么不将其转换Vec<u8>为字节切片呢?

\n

请记住,您可以轻松地&[u8]Vec<T>. derefVec<u8> 强制执行:[u8]Deref<Target=[u8]>

\n
let v = b"Hello".to_vec();\nlet a: &[u8] = &v;\n
Run Code Online (Sandbox Code Playgroud)\n

您还可以as_slice()致电Vec<u8>

\n
let a = v.as_slice();\n
Run Code Online (Sandbox Code Playgroud)\n

这可能是您想要的,因为您可能正在使用 aVec来在运行时更改长度。

\n