【问题标题】:How to compare 2 enum variables?如何比较 2 个枚举变量?
【发布时间】:2021-05-13 13:02:18
【问题描述】:

下面是我在 Rust 中比较 2 个 enum 变量的代码。

I uploaded the code into playground here..

非常简单,我只想使用相等运算符 (==) 来比较两个枚举变量。提前谢谢你。

我的枚举:

use std::fmt::Display;

#[derive(Display)]
enum Fruits {
    Apple, 
    Orange,
}
// I try to use ToString but Rust cannot find derive macro `Display` in this scope
// ERROR: 
// doesn't satisfy `Fruits: ToString`
// doesn't satisfy `Fruits: std::fmt::Display`

// had to implement PartialEq for Fruits
impl PartialEq for Fruits {
    fn eq(&self, other: &Self) -> bool {
        self.to_string() == other.to_string()
        // here, I'm trying to use string conversion to compare both enum
        // it displays an error: 
        // method cannot be called on `&Fruits` due to unsatisfied trait bounds
    }
}

我的 main.rs:

fn main(){
    let a = Fruits::Apple;
    let b = Fruits::Orange;
    let c = Fruits::Apple;
    
    if a == c {
        println!("Correct! A equals with C !");
    }
    
    
     if a != b {
        println!("Correct! A is not equal with B !");
    }
    
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    如果您想比较枚举变体,请不要构建然后比较字符串。

    比较枚举变体(和大多数结构)的简单解决方案是派生PartialEq

    #[derive(PartialEq)]
    enum Fruits {
        Apple, 
        Orange,
    }
    fn main() {
        dbg!(Fruits::Apple == Fruits::Orange); // false
        dbg!(Fruits::Orange == Fruits::Orange); // true
    }
    

    【讨论】:

    • 更简单的解决方案。不知道#[derive(PartialEq)]能不能这样推导出来。谢谢。
    【解决方案2】:

    如何派生Debug 而不是Display?无法导出显示。

    #[derive(Debug)]
    enum Fruits {
        Apple, 
        Orange,
    }
    
    impl PartialEq for Fruits {
        fn eq(&self, other: &Self) -> bool {
            format!("{:?}", self) == format!("{:?}", other)
        }
    }
    
    fn main(){
        let a = Fruits::Apple;
        let b = Fruits::Orange;
        let c = Fruits::Apple;
        
        if a == c {
            println!("Correct! A equals with C !");
        }
         if a != b {
            println!("Correct! A is not equal with B !");
        }
    }
    

    【讨论】:

    • format!("{:?}", self) == format!("{:?}", other) 为我工作。但是生产可以吗?它不应该只用于调试(因此得名 Debug)吗?
    • 我没有看到像这样使用它有任何明显的问题。我觉得还可以。
    • 我接受它作为答案,但我很好奇是否还有其他方法
    • 对于生产,你可能根本不想比较字符串表示,而是#[derive(PartialEq)]
    • 我同意,我完全忘记了 PartialEq 可以很容易地推导出来。你是对的,当然。
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2012-05-04
    • 2017-02-08
    相关资源
    最近更新 更多