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

tin*_*ker 1 arrays assert slice rust

我已经编写了一些测试,我需要声明两个数组相等.有些阵列[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);
}
Run Code Online (Sandbox Code Playgroud)

我在这里收到多个错误:

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`
Run Code Online (Sandbox Code Playgroud)

试图将它们打印为像t2[..]t1[..]似乎不起作用的切片.

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

Mas*_*ara 6

使用切片

作为一种解决方法,您可以使用&t1[..](而不是t1[..])将数组转换为切片.您必须为比较和格式化执行此操作.

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

要么

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

直接格式化数组

理想情况下,原始代码应该编译,但现在不行.原因是由于缺少const泛型,标准库为最多32个元素的数组实现了共同的特征(例如EqDebug).

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

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


Fly*_*FoX 6

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

let mut t1: [u8; 48] = [0; 48];
let t2: [u8; 48] = [0; 48];
assert!(t1.iter().eq(t2.iter()));
Run Code Online (Sandbox Code Playgroud)


Hen*_*nke 5

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

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");
Run Code Online (Sandbox Code Playgroud)

  • 还有[`Iterator :: eq`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.eq) (4认同)
  • 还有[`itertools :: Itertools :: all_equal`](https://docs.rs/itertools/0.7.4/itertools/trait.Itertools.html#method.all_equal)就是这么做的. (2认同)