应为切片,但在断言它们相等时找到了数组



我试图断言两个切片相等,但其中一个切片被解释为数组:

#[derive(Debug, PartialEq)]
enum Error {
TooBig,
}
type Bytes = [u8];
struct Fixed {
length: u32,
}
impl<'a> Fixed {
pub fn new(length: u32) -> Fixed {
Fixed { length: length }
}
pub fn length(&self) -> u32 {
self.length
}
pub fn encode(&self, decoded: &'a Bytes) -> Result<&'a Bytes, Error> {
if decoded.len() > self.length() as usize {
Err(Error::TooBig)
} else {
Ok(&decoded)
}
}
pub fn decode(&self, decoded: &'a Bytes) -> Result<&'a Bytes, Error> {
if decoded.len() > self.length() as usize {
Err(Error::TooBig)
} else {
Ok(&decoded)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fixed_0() {
let length = 0;
let fixed = Fixed::new(length);
let encoded = [];
let decoded = [];
assert_eq!(fixed.length(), length);
assert_eq!(fixed.encode(&decoded), Ok(&encoded));
assert_eq!(fixed.decode(&encoded), Ok(&decoded));
assert_eq!(fixed.encode(&[1]), Err(Error::TooBig));
}
#[test]
fn fixed_1() {
let length = 1;
let fixed = Fixed::new(length);
let encoded: [u8; 1] = [1];
let decoded: [u8; 1] = [1];
assert_eq!(fixed.length(), length);
assert_eq!(fixed.encode(&decoded).unwrap(), &encoded);
assert_eq!(fixed.decode(&encoded).unwrap(), &decoded);
}
}

要点

这是我的错误:

error[E0308]: mismatched types
--> src/lib.rs:49:9
|
49 |         assert_eq!(fixed.encode(&decoded), Ok(&encoded));
|         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected slice, found array of 0 elements
|
= note: expected type `std::result::Result<&[u8], Error>`
found type `std::result::Result<&[_; 0], _>`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
error[E0308]: mismatched types
--> src/lib.rs:50:9
|
50 |         assert_eq!(fixed.decode(&encoded), Ok(&decoded));
|         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected slice, found array of 0 elements
|
= note: expected type `std::result::Result<&[u8], Error>`
found type `std::result::Result<&[u8; 0], _>`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

我对文档的阅读让我相信,通过使用&,我应该创建一个切片。我错过了什么?

您的示例可以简化为:

fn example(input: Result<&[u8], ()>) {
assert_eq!(input, Ok(&[]));
}

对数组的引用是对数组的参考,而不是切片。在许多上下文中,对数组的引用可能被强制到切片,但不是所有地方。这是一个不可能的情况。

使用更明确的切片语法:

assert_eq!(input, Ok(&[][..]));

另请参阅:

  • assert_eq!(a,b(在断言时无法编译切片!(a==b(运行良好
  • 什么';当两个选项包含可以测试相等性的值时,测试它们相等性的最常用方法是什么
  • 在Rust中,切片和数组的比较是如何工作的

最新更新