cairo by example


An enum in Cairo works like a tagged union, variants can hold values inside, which you can access via pattern matching.

You can work with enums like this:

use option::OptionTrait;
use debug::PrintTrait;

// Define an enum
enum MyEnum {
    A: u8,
    B: u16,
    C: u32,
    D: u64

// It will print 'Got something else'
fn main() {
    let x = my_enum_a();
    let y = my_enum_get_b(x);
    match y {
        Option::Some(x) => 'Got B'.print(),
        Option::None(()) => 'Got something else'.print(),

// Construct and return an enum variant.
fn my_enum_a() -> MyEnum {

// Match the enum, the order must match the enum definition.
// Option is also an enum.
fn my_enum_get_b(x: MyEnum) -> Option::<u16> {
    match x {
        MyEnum::A(x) => Option::None(()),
        MyEnum::B(x) => Option::Some(x),
        MyEnum::C(x) => Option::None(()),
        MyEnum::D(x) => Option::None(()),

To try the example simply run cairo-run --single-file enums.cairo in your terminal.

Try it out!
  1. Install the toolchain:
    • For macOS and Linux, run our script:
    • curl -sL | bash -s 2.2.0
    • For Windows and others, please see the official guide
  2. Run the example:
    1. Copy the example into a enums.cairo file and run with:
    2. %!s(<nil>) enums.cairo

prev (constants) next (tuples)