在Rust中能够逐个元素地比较两个向量或字符串的最佳方法是什么?例如,如果您想保留不同元素的数量。这就是我正在使用的:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
if x != y {
diff_count += 1i32;
}
}
这是正确的方法还是还有更多规范的方法?
fn main() {
let a = "Hello";
let b = "World";
let matching = a.chars().zip(b.chars()).filter(|&(a, b)| a == b).count();
println!("{}", matching);
let a = [1,2,3,4,5];
let b = [1,1,3,3,5];
let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count();
println!("{}", matching);
}
fn do_vecs_match<T : PartialEq>(a : &Vec<T>, b : &Vec<T>) -> bool {
let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count();
matching == a.len() && matching == b.len()
}
当然,在浮子上使用时要小心!那些讨厌的NaN不会比较,您可能需要使用公差来比较其他值。您可能想通过告诉第一个不匹配值的索引来使其花哨。