To get the count of matching elements, I'd probably use filter
and count
.
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).filter(|&(a, b)| a == b).count();
println!("{}", matching);
}
Iterator::zip
takes two iterators and produces another iterator of the tuple of each iterator's values.
Iterator::filter
takes a reference to the iterator's value and discards any value where the predicate closure returns false
. This performs the comparison.
Iterator::count
counts the number of elements in the iterator.
Note that Iterator::zip
stops iterating when one iterator is exhausted. If you need different behavior, you may also be interested in
Itertools::zip_longest
or Itertools::zip_eq
.