Skip to Content
Course content

26: Practice Exercise: Modeling a Shape Hierarchy with Enums

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you're coming from a language like Java or C#, your instinct for handling a "hierarchy" of objects—like different types of shapes—is usually to look for inheritance. Since Rust doesn't have classes or inheritance, I often see developers try to mimic that behavior using a "God Struct." It's a common pattern, but in Rust, it's almost always the wrong way to go.

The "One Size Fits All" Struct

Imagine we're building a simple geometry engine. You might be tempted to create a single Shape struct that contains every possible field any shape could ever need, and then add a tag to tell you which one it actually is. It looks something like this:

enum ShapeType {
    Circle,
    Rectangle,
}

struct Shape {
    shape_type: ShapeType,
    radius: Option<f64>,
    width: Option<f64>,
    height: Option<f64>,
}

At first glance, this feels flexible. You have one type to pass around your application, and you can just check the shape_type to decide which fields to read. I've seen this pattern in legacy C code for decades, and it feels familiar. But here's the problem: you've just created a state space that is far larger than your actual domain.

The Cost of Invalid States

The issue with the struct approach is that it allows for impossible objects. What happens if you create a Shape where the type is Circle, but the radius is None and the width is Some(10.0)? The compiler can't help you here. Your data is lying to you.

Every time you want to calculate an area, you're forced to write defensive code. You can't just use the radius; you have to unwrap() it or handle the None case, even though you know a circle should have a radius. You end up with a codebase littered with .expect("This should never happen") calls. When your types allow for invalid states, you're essentially pushing the burden of correctness from the compiler onto your own memory. That's a losing battle.

Leveraging Algebraic Data Types

This is where Rust's enums—which are actually sum types—really shine. Instead of a struct that might have some data, we use an enum where each variant owns its specific data. This collapses the state space so that only valid shapes can exist.

enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
    Square { side: f64 },
}

Now, it is physically impossible to have a Circle without a radius, or a Circle that accidentally has a width. The data and the label are bound together. When you process these shapes, you use a match statement, and Rust forces you to handle every single variant. If you add a Triangle variant later, the compiler will point to every single match block in your entire project and tell you exactly where you forgot to handle the new shape.

I always tell my juniors: if you find yourself using Option fields in a struct to represent "either-or" data, you don't have a struct; you have an enum that hasn't been written yet.




📋 Practical Task

Implementation: The Geometry Area Calculator

Your task is to build a small area calculation engine using an enum. This will move you away from the "optional field" mindset and into idiomatic Rust sum types.

  • Define an enum called Shape with the following variants:
    • Circle (containing a radius: f64)
    • Rectangle (containing width: f64 and height: f64)
    • Triangle (containing base: f64 and height: f64)
  • Implement a function calculate_area(shape: &Shape) -> f64 that uses a match statement to return the correct area for each variant. (Remember: Triangle area is 0.5 * base * height).
  • In your main function, create a Vec<Shape> containing one of each type, iterate through them, and print their areas.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.