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