【问题标题】:How to compare a slice with a vector in Rust?如何在 Rust 中将切片与向量进行比较?
【发布时间】:2017-11-14 02:32:56
【问题描述】:

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

答案一定很简单,但它让我难以捉摸。

【问题讨论】:

    标签: rust


    【解决方案1】:

    如错误消息所述:

    特征 std::cmp::PartialEq&lt;std::vec::Vec&lt;u8&gt;&gt; 未针对 [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)
    }
    

    切片相等的实现已经比较了两侧的长度,所以我也删除了它,同时切换到使用组合器。

    【讨论】:

    • n == fixed.len()read_to_end 是多余的,因为 n 总是等于 buf.len()buf == fixed 必须首先比较切片的长度。
    • @trentcl 部分读取意味着buf.len() 更短,但是是的,相等性检查确实长度。
    • 然而,我花了足够长的时间来确认,最好还是留下检查而不是做出假设。 :)
    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 2021-12-29
    • 2015-01-22
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多