Skip to content
This repository has been archived by the owner on Sep 25, 2024. It is now read-only.

Latest commit

 

History

History
48 lines (36 loc) · 1.25 KB

6. Data types II.md

File metadata and controls

48 lines (36 loc) · 1.25 KB

Data Types: Enums and Pattern Matching

In this section, we would be looking into Enums and Pattern Matching.

Enums

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)
}

Pattern Matching

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 the print() function.