0

我想知道,如果我有两个变量xy类型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>(特定专业化)重载/定义运算符?

4

1 回答 1

4

该类型Result<T, E> 已经实现PartialEq,因此您只需要为ErrorKind. 结果,该Result类型将实现它。

操场

于 2021-12-26T21:02:40.487 回答