Methods on tuples and enums
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
Here is an example of an instance method mood
defined on the variants of an Day
enum. It matches the variant to print out the mood
string of the day:
// see code in Chapter 6/code/method_enum.rs enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, } impl Day { fn mood(&self) { println!("{}", match *self { Day::Friday => "it's friday!", Day::Saturday | Day::Sunday => "weekend :-)", _ => "weekday...", }) } } fn main() { let today = Day::Tuesday; today.mood(); }
This prints out the following output:
weekday...