如何在Rust中比较切片和向量?

8
如何在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]`

答案一定很简单,但我却想不出来。
1个回答

8
正如错误信息所述:
“std :: cmp :: PartialEq >” 特性未实现 “[u8]”。
然而,相反的情况已经实现了:请参考此处
Ok(n) => Ok(n == fixed.len() && buf == fixed),

此外,您需要将参数标记为可变:mut reader: RRead::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)
}

比较切片的等式实现已经比较了两侧的长度,所以我在切换到使用组合器时也删除了这个部分。

n == fixed.len()read_to_end 冗余,因为 n 总是等于 buf.len(),而 buf == fixed 必须先比较切片的长度。 - trent
@trentcl 部分读取意味着 buf.len() 更短,但是是的,相等检查仍然会检查长度。 - Shepmaster
然而,我花了很长时间才确认这一点,也许最好还是保留检查而不是做出假设。 :) - trent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接