Methods can be attached to an enum type. Thus, instead of defining
an independent function that takes an enum as argument (i.e.:
my_function(my_enum_value)), we can define a method attached to the
enum type. We will call this method directly onto the object:
my_enum_value.my_method().
Let us define a Suit enum for representing card suits:
#[derive(Debug, PartialEq)]
enum Suit {
Club,
Diamond,
Heart,
Spade,
}Using the impl statement we declare the is_black() method that
returns true for black color cards (i.e.: clubs and spades):
impl Suit {
fn is_black(&self) -> bool {
[Suit::Club, Suit::Spade].contains(self)
}
}We can call this method on any Suit instance:
for x in [Suit::Diamond, Suit::Club, Suit::Heart, Suit::Spade] {
if x.is_black() {
println!("{x:?}");
}
}Club
Spade
()