0
0
Rustprogramming~30 mins

Trait bounds in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Circle struct
Create a struct called Circle with one field radius of type f64.
Rust
Hint

Use struct Circle { radius: f64 } to define the shape.

2
Create the Shape trait
Create a trait called Shape with a method area that returns an f64.
Rust
Hint

Use trait Shape { fn area(&self) -> f64; } to define the trait.

3
Implement Shape for Circle
Implement the Shape trait for Circle. The area method should return 3.14 * radius * radius.
Rust
Hint

Use impl Shape for Circle { fn area(&self) -> f64 { 3.14 * self.radius * self.radius } }.

4
Write print_area function and call it
Write a function called print_area that accepts a generic parameter T with a trait bound Shape. Inside, print the area using println!("Area: {}", shape.area()). Then create a Circle with radius 5.0 and call print_area with it.
Rust
Hint

Use fn print_area(shape: &T) and call print_area(&circle) in main.