arraysrustsliceassert

Using assert_eq or printing large fixed sized arrays doesn't work


I have written some tests where I need to assert that two arrays are equal. Some arrays are [u8; 48] while others are [u8; 188]:

#[test]
fn mul() {
    let mut t1: [u8; 48] = [0; 48];
    let t2: [u8; 48] = [0; 48];

    // some computation goes here.

    assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1);
}

I get multiple errors here:

error[E0369]: binary operation `==` cannot be applied to type `[u8; 48]`
 --> src/main.rs:8:5
  |
8 |     assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `[u8; 48]`
  = 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[E0277]: the trait bound `[u8; 48]: std::fmt::Debug` is not satisfied
 --> src/main.rs:8:57
  |
8 |     assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1);
  |                                                         ^^ `[u8; 48]` cannot be formatted using `:?`; if it is defined in your crate, add `#[derive(Debug)]` or manually implement it
  |
  = help: the trait `std::fmt::Debug` is not implemented for `[u8; 48]`
  = note: required by `std::fmt::Debug::fmt`

Trying to print them as slices like t2[..] or t1[..] doesn't seem to work.

How do I use assert with these arrays and print them?


Solution

  • For the comparison part you can just convert the arrays to iterators and compare elementwise.

    assert_eq!(t1.len(), t2.len(), "Arrays don't have the same length");
    assert!(t1.iter().zip(t2.iter()).all(|(a,b)| a == b), "Arrays are not equal");