使用 assert_eq 或打印大型固定大小的数组不起作用

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

我已经编写了一些测试,其中我需要断言两个数组相等。有些数组是 [u8; 48] 而有些是 [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);
}

我在这里遇到多个错误:

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`

尝试像 t2[..]t1[..] 那样将它们打印成切片似乎不起作用。

如何使用 assert 这些数组并打印它们?

对于比较部分,您可以将数组转换为迭代器并逐元素进行比较。

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");

你可以用它们制作 Vecs。

fn main() {
    let a: [u8; 3] = [0, 1, 2];
    let b: [u8; 3] = [2, 3, 4];
    let c: [u8; 3] = [0, 1, 2];

    let va: Vec<u8> = a.to_vec();
    let vb: Vec<u8> = b.to_vec();
    let vc: Vec<u8> = c.to_vec();

    println!("va==vb {}", va == vb);
    println!("va==vc {}", va == vc);
    println!("vb==vc {}", vb == vc);
}

使用切片

作为解决方法,您可以只使用 &t1[..](而不是 t1[..])将数组制成切片。 比较和格式化

您必须这样做
assert_eq!(&t1[..], &t2[..], "\nExpected\n{:?}\nfound\n{:?}", &t2[..], &t1[..]);

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

直接格式化数组

理想情况下,原始代码应该可以编译,但目前还不能。原因是标准库implements common traits (such as Eq and Debug) for arrays of only up to 32 elements, due to lack of const generics.

因此,您可以比较和格式化更短的数组,例如:

let t1: [u8; 32] = [0; 32];
let t2: [u8; 32] = [1; 32];
assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1);

使用 Iterator::eq,可以比较任何可以变成迭代器的东西是否相等:

let mut t1: [u8; 48] = [0; 48];
let t2: [u8; 48] = [0; 48];
assert!(t1.iter().eq(t2.iter()));