0
0
Rustprogramming~30 mins

Generics with traits in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Generics with traits
📖 Scenario: You are building a simple program to compare the sizes of different shapes. Each shape has a method to calculate its area. You want to write a generic function that can work with any shape that can calculate its area.
🎯 Goal: Create a generic function that accepts any shape implementing a trait with an area method, and prints the area.
📋 What You'll Learn
Define a trait called Shape with a method area that returns a f64.
Create two structs: Circle with a radius field, and Rectangle with width and height fields.
Implement the Shape trait for both Circle and Rectangle.
Write a generic function called print_area that accepts any type implementing the Shape trait and prints its area.
💡 Why This Matters
🌍 Real World
Traits and generics let you write flexible code that works with many types, like shapes, without repeating code.
💼 Career
Understanding traits and generics is essential for Rust programming jobs, especially when building reusable libraries or complex systems.
Progress0 / 4 steps
1
Define the Shape trait and structs
Define a trait called Shape with a method area that returns a f64. Then create two structs: Circle with a radius field of type f64, and Rectangle with width and height fields of type f64.
Rust
Hint

Use trait to define the trait and struct to define the shapes with their fields.

2
Implement the Shape trait for Circle and Rectangle
Implement the Shape trait for the Circle struct by defining the area method that returns the area of the circle using the formula 3.14 * radius * radius. Then implement the Shape trait for the Rectangle struct by defining the area method that returns the area using width * height.
Rust
Hint

Use impl Shape for Circle and impl Shape for Rectangle to add the area method for each.

3
Write a generic function print_area
Write a generic function called print_area that accepts a parameter shape of any type that implements the Shape trait. Inside the function, print the area of the shape using shape.area().
Rust
Hint

Use fn print_area<T: Shape>(shape: T) to define the generic function.

4
Call print_area with Circle and Rectangle
Create a Circle instance with radius 3.0 and a Rectangle instance with width 4.0 and height 5.0. Then call the print_area function with both instances to print their areas.
Rust
Hint

Remember to create the instances with the exact field values and call print_area inside fn main().