Shape Area Calculator
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 61 of 61.
Challenge
EasyThis 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 theShapetrait with anareamethod that returns anf64. This trait establishes the contract that all shapes must fulfill.shapes.rs: Create two structs that implement your trait. ACirclehas aradius(f64), and aSquarehas aside(f64). Each struct should implement theShapetrait with its appropriate area formula. For circles, use3.14159as π.main.rs: Bring in both modules and create atotal_areafunction that accepts aVec<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.56636This 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.14159You 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
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock