Methods on Enums in Rust

beginner
24 min

Methods on Enums in Rust

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!

Enumerations (Enums) in Rust 🎯

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.

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

In this example, Shape is an Enum with two variants: Circle and Rectangle.

Methods on Enums 💡

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:

rust
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.

Pro Tip 📝

  • Enums can have multiple methods associated with them, just like structures.
  • You can also define methods for each variant individually using the impl Shape { ... } syntax.

Quiz Time! ✅

Quick Quiz
Question 1 of 1

Which function is called on the `circle` instance to calculate its area?

Stay tuned for more exciting tutorials on Rust! Happy coding! 🎉