Enums and Pattern Matching

Enums allow you to define a type by enumerating its possible variants.

Defining an Enum

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

Using Enums

let msg = Message::Write(String::from("Hello"));

Pattern Matching

match msg {
    Message::Quit => println!("Quit"),
    Message::Move { x, y } => println!("Move to ({}, {})", x, y),
    Message::Write(text) => println!("Text: {}", text),
    Message::ChangeColor(r, g, b) => println!("Color: {},{},{}", r, g, b),
}
← PrevNext →