如何在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]`
答案一定很简单,但我却想不出来。
n == fixed.len()
与read_to_end
冗余,因为n
总是等于buf.len()
,而buf == fixed
必须先比较切片的长度。 - trentbuf.len()
更短,但是是的,相等检查仍然会检查长度。 - Shepmaster