我已经编写了一些测试,我需要声明两个数组相等。有些数组是[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
与这些数组一起使用并打印出来?
答案 0 :(得分:6)
对于比较部分,您可以将数组转换为迭代器并进行元素比较。
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");
答案 1 :(得分:6)
作为解决方法,您只需使用 &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(例如Eq
和Debug
)适用于最多32个元素的数组,原因是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);
答案 2 :(得分:3)
使用Iterator::eq
,可以将任何可以转换为迭代器的内容进行比较:
let mut t1: [u8; 48] = [0; 48];
let t2: [u8; 48] = [0; 48];
assert!(t1.iter().eq(t2.iter()));
答案 3 :(得分: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);
}