如何比较2个枚举变量?

Den*_*Hiu 1 rust

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

我在这里将代码上传到了操场上。.

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

我的枚举:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 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 !");
    }
    
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 6

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

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

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