Menu
Coddy logo textTech

Shape Area Calculator

Part of the Object Oriented Programming section of Coddy's Rust journey. Lesson 61 of 61.

challenge icon

Challenge

Easy

This final challenge brings together traits, trait objects, and polymorphism to solve a practical problem: calculating the total area of different shapes stored in a single collection.

Let's build a shape area calculator that demonstrates the power of trait objects and polymorphism! You'll create a system where different shapes—circles and squares—can be stored together in a single collection and have their total area calculated through a unified interface.

You'll organize your code across three files:

  • shape.rs: Define the Shape trait with an area method that returns an f64. This trait establishes the contract that all shapes must fulfill.
  • shapes.rs: Create two structs that implement your trait. A Circle has a radius (f64), and a Square has a side (f64). Each struct should implement the Shape trait with its appropriate area formula. For circles, use 3.14159 as π.
  • main.rs: Bring in both modules and create a total_area function that accepts a Vec<Box<dyn Shape>> and returns the sum of all areas. Using the provided inputs, create a circle and a square, store them in a vector of trait objects, calculate the total area, and print the result.

The area formulas are:

  • Circle: 3.14159 × radius × radius
  • Square: side × side

Your output should display the total area of all shapes:

Total area: {total}

For example, with inputs 2.0 (circle radius) and 3.0 (square side):

Total area: 21.56636

This is because: Circle area = 3.14159 × 2² = 12.56636, Square area = 3² = 9, Total = 21.56636

And with inputs 1.0 and 4.0:

Total area: 19.14159

You will receive two inputs: the circle's radius and the square's side length (parse both as f64).

Try it yourself

mod shape;
mod shapes;

use shape::Shape;
use shapes::{Circle, Square};

// TODO: Implement the total_area function
// It should accept a Vec<Box<dyn Shape>> and return the sum of all areas as f64
fn total_area(shapes: Vec<Box<dyn Shape>>) -> f64 {
    // TODO: Calculate and return the sum of all shape areas
    0.0
}

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

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

    // TODO: Create a Circle with the given radius
    // TODO: Create a Square with the given side
    // TODO: Store both shapes in a Vec<Box<dyn Shape>>
    // TODO: Call total_area and print the result in the format: "Total area: {total}"
}

All lessons in Object Oriented Programming

Practice on your own: Online Rust compiler