Rust Enum in python

Share this article

In Rust, an enum (short for “enumeration”) is a type that can have multiple possible variants. Each variant can optionally carry additional data. Enums are used when a value could represent one of several different things, allowing you to define a type by listing its possible values.

Example

enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let direction = Direction::North;

    match direction {
        Direction::North => println!("Going north!"),
        Direction::South => println!("Heading south!"),
        Direction::East => println!("Traveling east!"),
        Direction::West => println!("Moving west!"),
    }
}

What it does

In this example, we define an enum called Direction that can take one of four values: North, South, East, or West. We then use a match statement to check the variant and print a corresponding message.

  • Fixed Variants: Each variant (North, South, etc.) represents a possible state that Direction can have.

Examples

Example 1: Enum with different types of data

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

fn main() {
    let msg = Message::Move { x: 10, y: 20 };

    match msg {
        Message::Quit => println!("Quit message received."),
        Message::Move { x, y } => println!("Moving to coordinates: ({}, {})", x, y),
        Message::Write(text) => println!("Writing: {}", text),
        Message::ChangeColor(r, g, b) => println!("Changing color to: ({}, {}, {})", r, g, b),
    }
}

Here, the Message enum has four variants: Quit, Move, Write, and ChangeColor. Each variant can store different types of data. Move contains two integers (x and y), while Write holds a String.

Example 2: Enum with methods

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

impl TrafficLight {
    fn duration(&self) -> u32 {
        match self {
            TrafficLight::Red => 60,
            TrafficLight::Yellow => 5,
            TrafficLight::Green => 30,
        }
    }
}

fn main() {
    let light = TrafficLight::Red;
    println!("The light is red for {} seconds.", light.duration());
}

You can add methods to enums using impl. Here, we define a duration method for the TrafficLight enum, which returns the duration of each light in seconds.

Example 3: Using Option Enum

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

fn main() {
    match divide(4.0, 2.0) {
        Some(result) => println!("Result: {}", result),
        None => println!("Cannot divide by zero."),
    }
}

Rust’s standard library provides many useful enums, such as Option. In this example, Option is used to handle cases where a division might fail (like dividing by zero). Option has two variants: Some and None.

Example 4: Enums with custom data

enum Shape {
    Circle(f64),       // Holds the radius
    Rectangle(f64, f64),  // Holds width and height
}

fn area(shape: Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => 3.14 * radius * radius,
        Shape::Rectangle(width, height) => width * height,
    }
}

fn main() {
    let circle = Shape::Circle(5.0);
    let rectangle = Shape::Rectangle(4.0, 6.0);

    println!("Area of circle: {}", area(circle));
    println!("Area of rectangle: {}", area(rectangle));
}

Enums can hold custom data, like the Shape enum with Circle and Rectangle variants. Each variant stores different data types relevant to its shape, which you can use in calculations like area.