预期为片,断言它们相等时找到一个数组

时间:2018-11-02 21:12:48

标签: types rust slice

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

#[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);
    }
}

gist

这是我的错误:

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)

我对docs的阅读使我相信,通过使用&,我应该创建一个切片。我想念什么?

1 个答案:

答案 0 :(得分:3)

您的示例可以简化:

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

对数组的引用是对数组的引用,而不是切片。在许多情况下,对数组的引用可能被强制限制为切片,但并非无处不在。这是无法做到的。

请改用更明确的切片语法:

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

另请参阅: