结果 <T, E> 的相等性 Operator/Trait ==
Equality Operator/Trait == for Result<T, E>
我想知道,如果我有两个 Result<T, E>
类型的变量 x
和 y
,我如何为它重载相等运算符 ==
?这样就可以很容易地检查 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
.
是否有可能以某种方式 overload/define operator ==
for Result<T, E>
(generic) or Result<i32, ErrorKind>
(specific specialisation)?
类型 Result<T, E>
already implements PartialEq
,因此您只需要为 ErrorKind
派生该特征。 Result
类型将因此实现它。
我想知道,如果我有两个 Result<T, E>
类型的变量 x
和 y
,我如何为它重载相等运算符 ==
?这样就可以很容易地检查 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
.
是否有可能以某种方式 overload/define operator ==
for Result<T, E>
(generic) or Result<i32, ErrorKind>
(specific specialisation)?
类型 Result<T, E>
already implements PartialEq
,因此您只需要为 ErrorKind
派生该特征。 Result
类型将因此实现它。