Suppose we have:
impl T {
pub fn special_equal(&self, rhs: &T) -> bool;
}
Suppose we can NOT implement Eq (it needs to be reserved for another purpose)
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.
2e71828
October 24, 2020, 11:20am
2
Something like this should work (untested):
fn foo(lhs: &[T], rhs: &[T]) -> bool {
lhs.len() == rhs.len() && lhs.iter()
.zip(rhs)
.all(|(l,r)| l.special_equal(r))
}
(Edited accorded to @kornel ’s suggestion)
6 Likes
kornel
October 24, 2020, 11:21am
3
BTW: never use &Vec<T>
as an argument type. Use &[T]
instead. It's more flexible and avoids double indirection.
3 Likes
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
.
system
Closed
January 23, 2021, 2:56am
8
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.