Skip to content
Rust

Enum

Enums and Option.

By EZ4Code Team
enumenum

Code

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

impl Message {
    fn call(&self) {
        match self {
            Message::Quit => println!("Quit"),
            Message::Move { x, y } => println!("Move to ({}, {})", x, y),
            Message::Write(text) => println!("Write: {}", text),
            Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
        }
    }
}

// Option enum
fn divide(a: f64, b: f64) -> Option<f64> {
    if b == 0.0 {
        None
    } else {
        Some(a / b)
    }
}

fn main() {
    let msgs = vec![
        Message::Quit,
        Message::Move { x: 10, y: 20 },
        Message::Write("hello".to_string()),
    ];
    for msg in &msgs {
        msg.call();
    }

    match divide(10.0, 2.0) {
        Some(result) => println!("10 / 2 = {}", result),
        None => println!("Cannot divide by zero"),
    }

    // if let
    if let Some(result) = divide(10.0, 0.0) {
        println!("{}", result);
    } else {
        println!("Divide by zero");
    }
}

Explanation

Rust enums can carry data; Option<T> replaces null; match and if let handle enum variants.

More Rust Snippets