Enum in Cairo#
This article uses the Cairo compiler version: 2.0.0-rc0. Since Cairo is being rapidly updated, the syntax may vary slightly in different versions, and the article content will be updated to the stable version in the future.
Enums in Cairo are a group of enumerated types, or multiple subtypes that share a common enumerated type. The applicable scenario is when there is a group of types with common characteristics, but each type has many differences and is mutually exclusive at the same time.
Basic Usage Introduction#
For example, there are two versions of IP, IPV6 & IPV4. These two versions are also the version numbers of IP, and the same value can only be one of these types. In this case, enums can be used. The definition is as follows.
enum IpAddrKind {
V4:(),
V6:(),
}
Using Enum to instantiate variables
let four = IpAddrKind::V4(());
let six = IpAddrKind::V6(());
V4 and V6 can both be considered as a type IpAddrKind when passing parameters to a function.
#[derive(Drop)]
enum IpAddrKind {
V4: (),
V6: (),
}
fn route(ip_kind: IpAddrKind) {}
fn main() {
route(IpAddrKind::V4(()));
route(IpAddrKind::V6(()));
}
Adding Types to Enums#
Just like in 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 variables of the types are used as parameters for route.
Adding impl to Enums#
Just like we can add impl to structs in Rust to define functions, we can also use it 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.