【问题标题】:Equality Operator/Trait == for Result<T, E>相等运算符/特征 == 用于 Result<T, E>
【发布时间】:2021-12-26 20:52:58
【问题描述】:

我想知道,如果我有两个变量xy 类型为Result&lt;T, E&gt;,我该如何为它重载相等运算符==?这样人们就可以轻松检查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&lt;T, E&gt;(通用)或Result&lt;i32, ErrorKind&gt;(特定专业化)重载/定义运算符==

【问题讨论】:

    标签: rust traits equality-operator


    【解决方案1】:

    Result&lt;T, E&gt;already implements PartialEq 类型,因此您只需为ErrorKind 派生该特征。 Result 类型将因此实现它。

    Playground

    【讨论】:

    • 哦,所以我的枚举中缺少#[derive(PartialEq)]。现在这是有道理的。谢谢!
    • @Phil-ZXX 没错。您会在ResultPartialEq 实现的链接中注意到,有一个特征绑定:T: PartialEq, E: PartialEq。这意味着 PartialEq 是为任何 Result 实现的,其中内部类型也实现了它。
    • 我希望编译器更有帮助。它说error[E0369]: binary operation == cannot be applied to type Result&lt;i32, ErrorKind&gt;。所以我认为这意味着我必须为Result 实现我自己的PartialEq,但我现在知道情况并非如此。
    • 错误信息很有用,但它描述了一个更普遍的问题。您正在尝试为您无法控制的类型实现特征。这通常称为orphan rule,是为了防止方法或特征的冲突实现——如果两个依赖项为标准库中的一个类型实现相同的特征会发生什么?编译器应该选择哪种方法。
    • 另外,您评论中的错误消息E0369 也很有帮助。您不能将== 应用于那个Result,因为PartialEq 没有为它实现(因为它没有为ErrorKind 实现)。您的问题、116 和117 中的其他消息是因为您尝试手动实现PartialEq,这就是孤儿规则发挥作用的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多