Vec<T> custom equality

  1. Suppose we have:
impl T {
  pub fn special_equal(&self, rhs: &T) -> bool;
  1. Suppose we can NOT implement Eq (it needs to be reserved for another purpose)

  2. Is there an idiomatic way to do special_equal on a Vec<T> ? The less elegant solution is:

fn foo(lhs: &Vec<T>, rhs: &Vec<T> -> bool {
  if lhs.len() != rhs.len() { return false; }
  for i in 0..lhs.len() {
    if !lhs[i].special_equal(rhs[i]) { return false; }
  return true;

I am wondering if there is some builtin that can be used to do this.

Something like this should work (untested):

fn foo(lhs: &[T], rhs: &[T]) -> bool {
    lhs.len() == rhs.len() && lhs.iter()
                                 .all(|(l,r)| l.special_equal(r))

(Edited accorded to @kornel’s suggestion)


BTW: never use &Vec<T> as an argument type. Use &[T] instead. It's more flexible and avoids double indirection.


If your equality check satisfies PartialEq constraints, you can create a newtype and implement PartialEq on it. Then, if you put values of this type in a Vec, its PartialEq implementation will forward to your custom implementation. The benefit is that it also works for any other collection, the find method of iterators, etc.

1 Like

Ignoring a field doesn't violate PartialEq.