rust lang enum

The Rust programming language provides an enum construct that allows you to define a type that can have a fixed set of values. Enums in Rust are useful for representing a type that can have multiple possible values. Here is an example of how to define and use an enum in Rust:

enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let color = Color::Red;

    match color {
        Color::Red => println!("The color is red!"),
        Color::Green => println!("The color is green!"),
        Color::Blue => println!("The color is blue!"),
    }
}

In this example, we define an enum called Color with three possible values: Red, Green, and Blue. We then create a variable color and assign it the value Color::Red. We use a match statement to check the value of color and print a message based on its value.

Enums in Rust can also have associated data. This allows you to attach additional information to each variant of the enum. Here is an example:

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
    Square(f64),
}

fn main() {
    let shape = Shape::Circle(3.14);

    match shape {
        Shape::Circle(radius) => println!("The shape is a circle with radius {}.", radius),
        Shape::Rectangle(width, height) => println!("The shape is a rectangle with width {} and height {}.", width, height),
        Shape::Square(side) => println!("The shape is a square with side {}.", side),
    }
}

In this example, we define an enum called Shape with three possible variants: Circle, Rectangle, and Square. Each variant has associated data: the Circle variant has a radius, the Rectangle variant has a width and height, and the Square variant has a side length. We create a variable shape and assign it the value Shape::Circle(3.14). We use a match statement to check the value of shape and print a message based on its variant and associated data.

I hope this explanation helps! Let me know if you have any further questions.