Welcome back to CodeYourCraft, your friendly guide for learning programming! Today, we're diving into the exciting world of Enums and their methods in Rust. Let's get started!
In Rust, an Enum (short for Enumeration) is a user-defined data type that represents a set of values. Enums can be used to create a custom data type made up of several variants.
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}In this example, Shape is an Enum with two variants: Circle and Rectangle.
Just like structures, enums can have associated functions and impl blocks to define methods for each variant. Let's see an example of methods on enums:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(radius) => 3.14 * radius * radius,
Shape::Rectangle(length, width) => length * width,
}
}
}
fn main() {
let circle = Shape::Circle(5.0);
let rectangle = Shape::Rectangle(4.0, 6.0);
println!("Circle Area: {}", circle.area());
println!("Rectangle Area: {}", rectangle.area());
}In the example above, we have defined a method area for the Shape Enum that calculates the area for each variant. In the main function, we create instances of Shape for a circle and a rectangle and call the area method on each.
impl Shape { ... } syntax.Which function is called on the `circle` instance to calculate its area?
Stay tuned for more exciting tutorials on Rust! Happy coding! 🎉