#237 Jul 3, 2026

237. Iterator::eq — Compare Two Sequences Without Collecting Them First

Comparing a Vec to an array, or a filtered iterator to an expected result? You don’t need to collect() both sides into the same type first.

The usual reflex is to force both sequences into matching containers so == works:

1
2
3
4
5
let v = vec![1, 2, 3];
let a = [1, 2, 3];

// Allocates a throwaway Vec just to compare.
assert_eq!(v, a.to_vec());

Iterator::eq compares element-by-element straight off the iterators. No allocation, and the two sides don’t even have to be the same container type:

1
2
3
4
let v = vec![1, 2, 3];
let a = [1, 2, 3];

assert!(v.iter().eq(a.iter()));

It short-circuits, so a length or value mismatch stops early instead of walking both sequences to the end:

1
assert!([1, 2, 3].iter().ne([1, 2].iter()));

The real payoff is comparing a lazy chain to an expected sequence without materializing it:

1
2
let evens = (1..=6).filter(|n| n % 2 == 0);
assert!(evens.eq([2, 4, 6]));

And the same family does lexicographic ordering, again with no intermediate Vec:

1
2
3
4
use std::cmp::Ordering;

assert_eq!([1, 2, 3].iter().cmp([1, 2, 4].iter()), Ordering::Less);
assert!([1, 2].iter().lt([1, 3].iter()));

So the toolkit is eq, ne, cmp, lt, le, gt, ge — full equality and ordering over any two iterators, no collecting required.

← Previous 236. Result::flatten — Collapse a Result<Result<T, E>, E> in One Call Next → 238. slice::chunks_exact_mut — Edit a Slice in Fixed-Size Blocks Without Index Math