Now that we know a little bit about trait objects and how to work with them, let's use them in a different example, this challenge focuses on using Box<dyn Trait>
as fields in structs to encapsulate objects with dynamic behavior.
You need to define a trait called Renderable
and create two structs, Circle
and Rectangle
, that implement this trait. Then, you will create another struct called Canvas
, which can hold a collection of objects implementing the Renderable
trait. The Canvas
struct should have methods to add objects and render all objects.
Here are the requirements for the program, make sure to read them carefully:
Renderable
Traitrender(&self) -> String
to represent the object visually.Circle
and Rectangle
StructsCircle
should have a radius: f64
field.Rectangle
should have width: f64
and height: f64
fields.Renderable
TraitCircle
, the render
method should return a string like "Circle with radius X"
.Rectangle
, the render
method should return a string like "Rectangle with width X and height Y"
.Canvas
Structshapes
field that can store a Vec
of the Renderable trait objects.Canvas
:
new() -> Canvas
: Initializes an empty canvas.add_shape()
: Adds a shape to the canvas.render_all()
: Returns a vector of strings, each representing a rendered shape.⚠️ Make sure you make all the relevant items public with the pub
keyword, this is required for the tests to work.
If you're stuck, here are some hints to help you solve the challenge:
Box<dyn Trait>
to store objects with dynamic behavior. e.g.