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

标签 arrays rust slice assert

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

关于arrays - 使用 assert_eq 或打印大型固定大小的数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324359/

相关文章:

javascript - 使用 slice() 只返回前 5 个结果

c++ - 一次输入一行到c++中的字符串数组

javascript - 为什么位置移动后我得到一个空数组?

arrays - 此方法的返回类型是切片还是借用数组?

rust - 是否可以在特征实现中使用局部变量?

Rust:如何返回对 Rc<RefCell<HashMap<K, V>> 值的引用?

arrays - 通过带有起始和长度说明符的引用传递静态/动态数组的切片

c++ - 奇怪的数组签名

arrays - 如何在范围循环上应用异步?

rust - 我可以将变量赋值与 if 结合使用吗?