Compare Sequences With Iterator eq_by
Verify two sequences agree element-wise under a custom predicate with eq_by, so whitespace-normalized comparisons and length mismatches need no index loop.
Code
fn main() {
let configured = ["192.168.1.10", "10.0.0.2", "172.16.0.5"];
let observed = ["192.168.1.10 ", "10.0.0.2", " 172.16.0.5"];
// eq_by 逐元素调用谓词:两边 trim 后相等即通过
let matches = configured.iter().eq_by(observed.iter(), |a, b| a.trim() == b.trim());
let changed = ["192.168.1.10", "10.0.0.9", "172.16.0.5"];
let differs = configured.iter().eq_by(changed.iter(), |a, b| a.trim() == b.trim());
// 长度不一致直接判 false,不会 panic
let shorter = ["192.168.1.10"];
let len_diff = configured.iter().eq_by(shorter.iter(), |a, b| a == b);
println!("whitespace only: {matches}");
println!("value differs: {differs}");
println!("length mismatch: {len_diff}");
}The predicate runs element by element
configured.iter().eq_by(observed.iter(), |a, b| a.trim() == b.trim()) walks both sequences in lockstep and applies the closure to each pair, so only the comparison logic — not an index loop, not a length check — lives in user code. Three comparisons are made against configured = ["192.168.1.10", "10.0.0.2", "172.16.0.5"]: the observed array with stray spaces, the changed array with one different value, and a one-element shorter array.
What the three verdicts print
whitespace only: true
value differs: false
length mismatch: false
The first passes because every pair matches after trim(). The second fails at the middle element (10.0.0.9 versus 10.0.0.2) — the closure decides, so “different” means whatever the predicate says. The third shows the length rule in the file’s own comment: unequal lengths return false directly, no panic.
The line that closes the comparison
let len_diff = configured.iter().eq_by(shorter.iter(), |a, b| a == b);
This call also swaps in a stricter predicate (plain equality, no trim) — the same method carries both the element-wise logic and the length semantics.
Interactive Tools for This Topic
FAQ
- What does Compare Sequences With Iterator eq_by print when run?
- Invoke the file as-is — the `whitespace only:`, `value differs:`, `length mismatch:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.