下面是我在 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 !");
}
}
答案 0 :(得分:6)
如果要比较枚举变体,请不要构建然后比较字符串。
比较枚举变体(和大多数结构)的简单解决方案是派生 PartialEq
:
#[derive(PartialEq)]
enum Fruits {
Apple,
Orange,
}
fn main() {
dbg!(Fruits::Apple == Fruits::Orange); // false
dbg!(Fruits::Orange == Fruits::Orange); // true
}
答案 1 :(得分:-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 !");
}
}