I want to know the needy of the eq,partial Eq,ord while dealing with Structures and Enums
One of the best examples of the utility of the traits you mention (or traits in general) is that it allows you to 1. write generic code that imposes requirements on type variables without knowing exactly what that type is, and 2. Use the abilities that a trait give you on inputs of functions and methods again without knowing exactly what the types are.
So for example:
#[derive(PartialEq)]
struct MyInt(i128);
fn silly_equals<T: PartialEq>(lhs: T, rhs: T) -> bool {
lhs == rhs
}
fn main() {
assert_eq!(silly_equals(42u8, 10u8+32u8)); // allowed because u8 implements PartialEq
assert_eq!(silly_equals(MyInt(42), MyInt(42))); // allowed because MyInt implements PartialEq
}
To expand on this: pretty much every "wrapper" or container type has an impl<T> Eq for ... where T: Eq
,including Cell<T>
, Box<T>
, Vec<T>
, Arc<T>
, and so on. They also have similar impls for Ord
, PartialEq
and PartialOrd
.
Also, the HashMap
and HashSet
containers require their key type to implement Eq
(and Hash
) because that's a critical piece of how hash tables work. Similarly, all of the standard sort()
functions require T: Ord
for obvious reasons.
This is why, in general, putting things into a wrapper or container in Rust doesn't throw away your ability to compare those things, put those things into a hash table, sort them, and so on.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.