In this section, we would be looking into Enums and Pattern Matching.
Enums are custom types that allow the creation of variants of a value under a single name.
Take, for instance, for an exam test, you are expected to either pass or fail and nothing else. Let's create an enum for that.
enum ExamResult {
Pass: (),
Fail: ()
}
Pass
and Fail
has null(not a type in Cairo) types here. But, we could have an enum whose variants has different types. Like, so:
enum Message {
Quit: (),
Echo: felt252,
Move: (u32, u32),
ChangeColor: (u8, u8, u8)
}
Now, imagine remarks were being given to students, based on their exam results, in this case the ExamResult
enum we mentioned above, the conventional way to do this would be using if statements
, but here we would use pattern matching
instead:
use debug::PrintTrait;
fn give_remark(result: ExamResult){
match result {
ExamResult::Pass => {
('Congratulations. You passed').print()
},
ExamResult::Fail => {
('Sorry. You didn't make it').print()
}
}
}
use debug::PrintTrait
gives us access to theprint()
function.