Rust enums
Created By: chatGPT
Enums in Rust are a powerful feature that allows you to define a type that can be one of several variants. Each variant can have data associated with it, making enums a flexible choice for modeling complex data types. An enum is defined using the
enum
keyword followed by its name and the variants it encompasses.enum Direction {
North,
South,
East,
West,
}
You can also attach data to each variant. For example, you might have an enum to represent different shapes, which can include various parameters for each shape.
enum Shape {
Circle(f64), // radius
Rectangle(f64, f64), // width and height
Triangle(f64, f64, f64), // sides
}
To use an enum, you can create instances of its variants and pattern match on them to take specific actions based on the variant being used. Here's how you can implement this:
fn describe_shape(shape: Shape) {
match shape {
Shape::Circle(radius) => println!("This is a circle with radius {}", radius),
Shape::Rectangle(width, height) => println!("This is a rectangle of width {} and height {}", width, height),
Shape::Triangle(a, b, c) => println!("This is a triangle with sides {}, {}, {}", a, b, c),
}
}
Enums also have the ability to implement methods. You can define functions that act upon the enum itself, allowing you to encapsulate behavior tied to specific variants.
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
This method enables you to compute the area of various shapes while keeping the logic organized within the enum itself. Using enums in Rust improves code clarity and strength, allowing for better type safety and logical structure.
fn main() {
let my_shape = Shape::Circle(2.0);
println!("Area: {}", my_shape.area());
}