我想知道,如果我有两个变量x
和y
类型Result<T, E>
,我该如何重载相等运算符==
呢?这样一来就可以轻松查到x == y
。这是一些示例代码,我在其中尝试过:
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);
}
不幸的是,这给了error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
.
我也尝试过impl MyResult { ... }
(没有PartialEq
),但这给出了error[E0116]: cannot define inherent 'impl' for a type outside of the crate where the type is defined
.
是否有可能以某种方式==
为Result<T, E>
(通用)或Result<i32, ErrorKind>
(特定专业化)重载/定义运算符?