enum in rust

An enum in Rust is a data type that allows you to define a type by enumerating its possible values. It is similar to an enumeration in other programming languages. The enum keyword is used to define an enum in Rust.

Here is the syntax for defining an enum in Rust:

enum EnumName {
    Variant1,
    Variant2,
    Variant3,
    // more variants...
}

Each value in the enum is called a variant, and variants are separated by commas. Variants can have associated data, which allows you to attach additional information to each variant. Here is an example of an enum with variants that have associated data:

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

In this example, the Shape enum has three variants: Circle, Rectangle, and Triangle. The Circle variant has an associated data of type f64, representing the radius of the circle. The Rectangle variant has two associated data of type f64, representing the width and height of the rectangle. The Triangle variant has three associated data of type f64, representing the lengths of the triangle's sides.

To use an enum, you can create variables of the enum's type and assign them one of the defined variants:

fn main() {
    let shape1 = Shape::Circle(3.14);
    let shape2 = Shape::Rectangle(2.0, 4.0);
    let shape3 = Shape::Triangle(1.0, 2.0, 3.0);
}

You can also use match statements to pattern match on the variants of an enum and perform different actions based on the matched variant:

fn print_area(shape: Shape) {
    match shape {
        Shape::Circle(radius) => println!("Area of circle: {}", 3.14  radius  radius),
        Shape::Rectangle(width, height) => println!("Area of rectangle: {}", width * height),
        Shape::Triangle(a, b, c) => {
            let s = (a + b + c) / 2.0;
            let area = (s  (s - a)  (s - b) * (s - c)).sqrt();
            println!("Area of triangle: {}", area);
        }
    }
}

fn main() {
    let shape1 = Shape::Circle(3.14);
    let shape2 = Shape::Rectangle(2.0, 4.0);
    let shape3 = Shape::Triangle(1.0, 2.0, 3.0);

    print_area(shape1);
    print_area(shape2);
    print_area(shape3);
}

In this example, the print_area function takes a Shape enum as an argument and uses a match statement to calculate and print the area of the shape based on its variant.

This is the basic usage of enum in Rust. Enums are a powerful tool for defining types with a finite set of values and can be used to improve the clarity and safety of your code.