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

标签 rust

我如何在 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/

相关文章:

rust - 将本地字符串作为切片返回 (&str)

rust - 我怎么知道 Rust 中是否初始化了某些东西?

rust - 如何格式化 const 字符串

c - 如何通过 LLVM C 绑定(bind)发出调试信息?

rust - 使用 serde 序列化时如何对 HashMap 键进行排序?

winapi - 获取硬盘所有逻辑驱动器号并收集根目录的有效方法

memory - 为什么内存地址打印的是{:p} much bigger than my RAM specs?

dataframe - 遍历行 polars rust

rust - 在 Rust 中的两个异步函数之间进行选择的变量 - 不兼容的 ARM 类型

rust - 在结构内部向下转换Box <dyn ForeignTrait>?