I'm new to Rust and I would like to implement a function to compare 2 collections of strings. The function should compare them as if they are unordered.
In Python, I would implement something like this:
from collections.abc import Iterator
def unordered_eq(a: Iterator[str], b: Iterator[str]):
a = sorted(a)
b = sorted(b)
assert a == b
I then tried implementing something similar in Rust. I'm trying to collect both iterators into new Vec<&str>
instances, then sort()
each of those vectors, then finally do a simple assert_eq!(a, b)
.
fn unordered_eq<'a, T, U>(a: T, b: U)
where
T: Iterator<Item = &'a str>,
U: Iterator<Item = &'a str>,
{
let mut a: Vec<&str> = a.collect();
let mut b: Vec<&str> = b.collect();
a.sort();
b.sort();
assert_eq!(a, b);
}
// Example usage:
struct Item { path: String };
let items: Vec<Item> = ...;
unordered_eq(
items.iter().map(|x| x.path.as_str()),
["hello", "hello2", "hello3", "hello4", "world"].iter().copied(),
)
Is this the correct / idiomatic way to implement this in Rust? How can I improve it?