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

问题描述 投票:0回答:5

我编写了一些测试,需要断言两个数组相等。有些数组是

[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
与这些数组一起使用并打印它们?

arrays rust slice assert
5个回答
10
投票

使用

Iterator::eq
,可以比较任何可以变成迭代器的相等性:

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

8
投票

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

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

7
投票

使用切片

作为解决方法,您可以使用

&t1[..]
(而不是
t1[..]
)将数组制作为切片。您必须这样做才能比较和格式化

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

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

直接格式化数组

理想情况下,原始代码应该可以编译,但目前还不能编译。原因是标准库最多 32 个元素的数组实现了共同特征

(例如
Eq
Debug),因为缺乏 const 泛型

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

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

0
投票

你可以用它们制作

Vec

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

0
投票

更新:

根据 Rust 文档,可以只使用

assert_eq!(array_0,array_1);

let a = arr3(&[[[ 1,  2,  3],     // -- 2 rows  \_
            [ 4,  5,  6]],    // --         /
           [[ 7,  8,  9],     //            \_ 2 submatrices
            [10, 11, 12]]]);  //            / 
let b = a.slice(s![.., 0..1, ..]);
let c = arr3(&[[[ 1,  2,  3]],
           [[ 7,  8,  9]]]);
assert_eq!(b, c);

https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html

© www.soinside.com 2019 - 2024. All rights reserved.