我如何在 Rust 中比较数组切片和向量?有问题的代码:
fn parse<R: io::Read>(reader: R, fixed: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; fixed.len()];
match reader.read(&mut buf) {
Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
Err(e) => Err(e)
}
}
我得到的错误:
error[E0277]: the trait bound `[u8]: std::cmp::PartialEq<std::vec::Vec<u8>>` is not satisfied
--> src/main.rs:32:47
|
32 | Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
| ^^ can't compare `[u8]` with `std::vec::Vec<u8>`
|
= help: the trait `std::cmp::PartialEq<std::vec::Vec<u8>>` is not implemented for `[u8]`
答案一定很简单,但它让我望而却步。
最佳答案
如错误消息所述:
the trait
std::cmp::PartialEq<std::vec::Vec<u8>>
is not implemented for[u8]
然而,opposite direction is implemented :
Ok(n) => Ok(n == fixed.len() && buf == fixed),
此外,您需要将参数标记为可变:mut reader: R
.
Read::read_exact
执行 n == fixed.len()
为您检查。
分配一个全为零的向量并不像它应该的那样有效。您可以改为限制输入并读入一个向量,边走边分配:
fn parse<R>(reader: R, fixed: &[u8]) -> io::Result<bool>
where
R: Read,
{
let mut buf = Vec::with_capacity(fixed.len());
reader
.take(fixed.len() as u64)
.read_to_end(&mut buf)
.map(|_| buf == fixed)
}
切片相等的实现已经比较了两侧的长度,所以我也删除了它,同时切换到使用组合器。
关于rust - 如何在 Rust 中比较切片和向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268301/