Menu
Coddy logo textTech

Recap - Shape Enum

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 18 of 61.

challenge icon

Challenge

Easy

Let's build a geometry calculator that uses an enum to represent different shapes, each storing its own dimensions. Your Shape enum will demonstrate how a single type can hold different data structures and provide unified behavior through methods.

You'll create two files to organize your code:

  • shape.rs: Define a public Shape enum with two variants:
    • Circle — holds a single f64 representing the radius (tuple syntax)
    • Rectangle — holds named fields: width (f64) and height (f64)
    Implement an area method that uses pattern matching to calculate the correct area based on the variant. For circles, use 3.14159 as π.
  • main.rs: Bring in your shape module, create one instance of each shape variant using the provided inputs, and print the area of each shape.

Your area method should return an f64. When matching, destructure each variant to extract its dimensions and apply the appropriate formula:

  • Circle area: π × radius²
  • Rectangle area: width × height

Your output should display the area of each shape on its own line, with exactly one decimal place:

Circle area: {area}
Rectangle area: {area}

For example, with a circle radius of 5.0 and a rectangle with width 4.0 and height 6.0, the output would be:

Circle area: 78.5
Rectangle area: 24.0

You will receive three inputs: the circle's radius, the rectangle's width, and the rectangle's height.

Try it yourself

mod shape;

use shape::Shape;

fn main() {
    // Read inputs
    let mut radius_input = String::new();
    std::io::stdin().read_line(&mut radius_input).expect("Failed to read line");
    let radius: f64 = radius_input.trim().parse().expect("Invalid number");

    let mut width_input = String::new();
    std::io::stdin().read_line(&mut width_input).expect("Failed to read line");
    let width: f64 = width_input.trim().parse().expect("Invalid number");

    let mut height_input = String::new();
    std::io::stdin().read_line(&mut height_input).expect("Failed to read line");
    let height: f64 = height_input.trim().parse().expect("Invalid number");

    // TODO: Create a Circle shape using the radius
    
    // TODO: Create a Rectangle shape using width and height
    
    // TODO: Print the area of each shape with one decimal place
    // Format: "Circle area: {area}" and "Rectangle area: {area}"
}

All lessons in Object Oriented Programming