I was wondering, if I have two variables x and y of type Result<T, E>, how can I overload the equality operator == for it? So that one can easily check x == y. Here is some sample code, where I tried just that:
enum ErrorKind {
OutOfRange,
InvalidInput,
}
type MyResult = Result<i32, ErrorKind>;
impl PartialEq for MyResult {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Ok(x), Ok(y)) => x == y,
(Err(x), Err(y)) => x == y,
_ => false,
}
}
}
fn func(x: i32) -> MyResult {
if x < 0 {
return Err(ErrorKind::OutOfRange);
} else {
return Ok(x);
}
}
fn main() {
let x = func(-1);
let y = func(15);
let z = func(15);
println!("x == z --> {}", x == z);
println!("y == z --> {}", y == z);
}
Unfortunately, this gives error[E0117]: only traits defined in the current crate can be implemented for arbitrary types.
I also tried impl MyResult { ... } (without the PartialEq) but that gives error[E0116]: cannot define inherent 'impl' for a type outside of the crate where the type is defined.
Is it possible to somehow overload/define operator == for Result<T, E> (generic) or Result<i32, ErrorKind> (specific specialisation)?
The type
Result<T, E>already implementsPartialEq, so you just need to derive that trait forErrorKind. TheResulttype will implement it as a consequence.Playground