0
0
Rustprogramming~30 mins

Trait objects overview in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Trait objects overview
📖 Scenario: Imagine you are building a simple drawing app. You want to store different shapes like circles and rectangles in one list and draw them all.
🎯 Goal: You will create a list of shapes using trait objects so you can call the draw method on each shape without knowing its exact type.
📋 What You'll Learn
Create a trait called Shape with a method draw
Create two structs: Circle and Rectangle
Implement the Shape trait for both structs
Create a vector of Box<dyn Shape> holding different shapes
Use a for loop to call draw on each shape
Print the drawing messages exactly as specified
💡 Why This Matters
🌍 Real World
Trait objects let you write flexible code that works with different types through a common interface. This is useful in graphics apps, game engines, and plugins.
💼 Career
Understanding trait objects is important for Rust developers to write clean, reusable, and extensible code that handles multiple types uniformly.
Progress0 / 4 steps
1
Create the Shape trait and structs
Create a trait called Shape with a method draw(&self) that returns nothing. Then create two structs called Circle and Rectangle with no fields.
Rust
Hint

Traits are like interfaces. Define Shape with fn draw(&self);. Then define empty structs Circle and Rectangle.

2
Implement Shape for Circle and Rectangle
Implement the Shape trait for Circle and Rectangle. For Circle, draw should print "Drawing a circle". For Rectangle, draw should print "Drawing a rectangle".
Rust
Hint

Use impl Shape for Circle and define fn draw(&self) to print the message. Do the same for Rectangle.

3
Create a vector of Box<dyn Shape> with shapes
Create a mutable vector called shapes of type Vec<Box<dyn Shape>>. Add a Box::new(Circle) and a Box::new(Rectangle) to the vector.
Rust
Hint

Use Vec<Box<dyn Shape>> to hold different shapes. Add shapes with shapes.push(Box::new(Circle)).

4
Call draw on each shape and print output
Use a for loop with shape to iterate over shapes.iter(). Inside the loop, call shape.draw(). This will print the drawing messages.
Rust
Hint

Use for shape in shapes.iter() and call shape.draw() inside the loop to print the messages.