StarknetAstro

StarknetAstro

05_Enum in Cairo

05_Cairo Enum#

The version of the Cairo compiler used in this article is 2.0.0-rc0. Because Cairo is being updated rapidly, the syntax may vary slightly in different versions, and the content of the article will be updated to the stable version in the future.

Enums in Cairo are a group of enumerated types, or multiple subtypes sharing a single enumerated type. The applicable scenario is: a group of types with common characteristics, but each type has many differences, and they are mutually exclusive at the same time.

Basic Usage Introduction#

For example: IP has two versions, IPV6 & IPV4. These two versions are also the version numbers of IP, and the same value can only be one of these types, so enums can be used. The definition is as follows.

enum IpAddrKind {
    V4:(),
    V6:(),
}

Instantiate variables using Enum

let four = IpAddrKind::V4(());
let six = IpAddrKind::V6(());

V4 and V6 can both be considered as a type IpAddrKind when passed as function arguments.

#[derive(Drop)] 
enum IpAddrKind {
    V4: (),
    V6: (),
}

fn route(ip_kind: IpAddrKind) {}

fn main() {
    route(IpAddrKind::V4(()));
    route(IpAddrKind::V6(()));
}

Adding Types to Enums#

Like Rust, we can add various types to enums, and each element in the enum is like an alias for a type.

#[derive(Drop)]
enum Message {
    Quit: (),
    Echo: felt252,
    Move: (usize, usize),
    ChangeColor: (u8, u8, u8)
}

fn route(msg: Message) {}

fn main() {
    route(Message::Quit(()));
    route(Message::Echo(20));
    route(Message::Move((32_usize, 32_usize)));
    route(Message::ChangeColor((8_u8, 8_u8, 8_u8)));
}

Above, felt252 and tuple are added to the enum Message, and the corresponding type variables are used as parameters for route.

Adding impl to Enums#

We can add impl to struct, define functions, and also use them on enums. The code example is as follows:

use debug::PrintTrait;

#[derive(Drop)]
enum Message {
    Quit: (),
    Echo: felt252,
    Move: (usize, usize),
    ChangeColor: (u8, u8, u8)
}

trait Processing {
    fn process(self: Message);
}

impl ProcessingImpl of Processing {
    fn process(self: Message) {
        match self {
            Message::Quit(()) => {
                'quitting'.print();
            },
            Message::Echo(value) => {
                value.print();
            },
            Message::Move((x, y)) => {
                'moving'.print();
            },
            Message::ChangeColor((x, y, z)) => {
                'ChangeColor'.print();
            },
        }
    }
}

This brings great richness to the data type.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.