From the course: Rust Essential Training
Unlock the full course today
Join today to access over 22,500 courses taught by industry experts or purchase this course individually.
Enum methods
- You can define methods that act on enums similar to defining methods for structs to demonstrate that let's implement a method for the shape enum, we defined in an earlier video to get the perimeter of the shape, which can be one of three possible enum types a circle, a rectangle, or a triangle. We'll start by creating an implementation block or the shape type, just like we would with a struct. Then within that block, let's define a function named get perimeter. It will have just one input parameter which is a reference to the enum named self and it will return a floating point value. Now, the equation to calculate the perimeter for each of the three shapes is different. So we need to determine which calculation to perform based on the type of shape. This is the perfect time to use a match expression. We'll perform a match on the reference to yourself. As a side note in past versions of Rust, we would also need to include…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.