Reputation: 1
I want to compare enum values when the enum types are the same. What should I do?
for example
#[derive(Debug, PartialEq, PartialOrd)]
enum Fruits {
Orange{weight: u8},
Banana{weight: u8},
Pear{weight: u8},
}
fn compare(fruit_a: Fruits,fruit_b: Fruits) -> bool {
// Fruits::Orange < Fruits::Banana < Fruits::Pear
// if same type, compare weight
if fruit_a < fruit_b {
return false;
}else if fruit_a == fruit_b {
todo!()
}else {
return true
}
}
I can't use a method like
let v = if let Fruits::Banana{weight} = fruit {
weight
}else {
0u8
};
Because I don't know what type follows Frutis::
Upvotes: 0
Views: 213
Reputation: 42632
I can't use a method like
let v = if let Fruits::Banana{weight} = fruit { weight } else { 0u8 };
Because I don't know what type follows Frutis::
That... is the point of if let
? If it's Fruits::Banana
it'll take the first branch, otherwise it'll take the second branch.
For a wider pick, with more flexibility, you can use match
:
let v = match fruit {
Fruits::Orange{weight} => weight,
Fruits::Banana{weight} => weight,
Fruits::Pear{weight} => weight,
}
Though do note that what follows Fruits::
is not a type, it's a variant tag (sometimes called "constructor", but more for singleton or tuple variants).
Anyway your entire line of questioning seems useless: what you're asking for is already the behaviour of Eq and Ord so you can just call [partial_]cmp
or ==
on your structures directly, and it'll do exactly what you're looking for, compare the variants first, then compare the variant' values if the values are the same variants:
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]
enum Fruits {
Orange { weight: u8 },
Banana { weight: u8 },
Pear { weight: u8 },
}
fn main() {
println!(
"{:?}",
Fruits::Orange { weight: 5 }.cmp(&Fruits::Pear { weight: 2 })
);
// Less, because Orange < Pear
println!(
"{:?}",
Fruits::Orange { weight: 7 }.cmp(&Fruits::Orange { weight: 5 })
);
// Greater, because 7 > 5
}
Upvotes: 1