Trait bounds
📖 Scenario: You are building a small Rust program that works with different types of shapes. Each shape can calculate its area. You want to write a function that can accept any shape, as long as it can calculate its area.
🎯 Goal: Create a trait called Shape with a method area. Then write a function print_area that accepts any type implementing the Shape trait and prints its area.
📋 What You'll Learn
Create a trait named
Shape with a method area that returns an f64.Create a struct
Circle with a field radius of type f64.Implement the
Shape trait for Circle.Create a function
print_area that accepts a generic parameter with a trait bound Shape.Call
print_area with a Circle instance and print the area.💡 Why This Matters
🌍 Real World
Traits let you write flexible code that works with many types sharing common behavior, like shapes calculating area.
💼 Career
Understanding trait bounds is essential for writing reusable and safe Rust code, a key skill for Rust developers.
Progress0 / 4 steps