Problem overview
A drawing app keeps rectangles, squares and triangles in one list. The code that works on the list should be able to ask any shape for its name and its perimeter without knowing which kind it holds. That is polymorphism: one call, shape.perimeter(), and each kind of shape runs its own version.
You write the trait Shape, three structs that implement it, and two functions, total_perimeter and largest_shape. The perimeters are 2 × (width + height) for Rectangle, 4 × side for Square and a + b + c for Triangle.
For a rectangle 3 by 4, a square of side 5 and a triangle with sides 3, 4 and 5, the perimeters are 14, 20 and 12. The total is 46, and the square has the largest perimeter, so the answer is 46 Square.
Approach: one trait, a list of boxes
Rust has no classes, so the common type is a trait. Shape declares two methods without bodies, which means every type that implements it must write both. Each struct then has its own impl Shape for ... block.
The three structs have different sizes in memory, so a plain Vec can't hold them directly. A Box<dyn Shape> is a pointer to any value that implements Shape, and every such box has the same size. A Vec<Box<dyn Shape>> can therefore mix the three kinds.
The two functions only use the trait's methods. They never check which kind of shape they have, so a fourth kind of shape added later works with them unchanged.
Step by step
- Declare the trait's methods.
namereturns aStringandperimeterreturns ani32. Each ends with a semicolon in place of a body. - Give each struct its fields.
Rectanglekeepswidthandheight,Squarekeepsside,Trianglekeepsa,bandc. The perimeter is worked out later from these fields. - Write each
new. It ends with a struct expression. When a field and the variable holding its value share a name, writing the name once is enough:Rectangle { width, height }. - Write each
nameandperimeter. The name is a string literal turned into aStringwithto_string(), and the perimeter is the formula for that shape. - Write
total_perimeter. Start alet mut total = 0, loop over the shapes and addshape.perimeter()each time. End withtotaland no semicolon. - Write
largest_shape. Start withlargestas a borrow of the first shape,&shapes[0], which exists because the list is never empty. Loop over all the shapes and replacelargestonly when a perimeter is strictly greater. End withlargest.name().
The solution in Rust
trait Shape {
fn name(&self) -> String;
fn perimeter(&self) -> i32;
}
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
fn new(width: i32, height: i32) -> Rectangle {
Rectangle { width, height }
}
}
impl Shape for Rectangle {
fn name(&self) -> String {
"Rectangle".to_string()
}
fn perimeter(&self) -> i32 {
2 * (self.width + self.height)
}
}
struct Square {
side: i32,
}
impl Square {
fn new(side: i32) -> Square {
Square { side }
}
}
impl Shape for Square {
fn name(&self) -> String {
"Square".to_string()
}
fn perimeter(&self) -> i32 {
4 * self.side
}
}
struct Triangle {
a: i32,
b: i32,
c: i32,
}
impl Triangle {
fn new(a: i32, b: i32, c: i32) -> Triangle {
Triangle { a, b, c }
}
}
impl Shape for Triangle {
fn name(&self) -> String {
"Triangle".to_string()
}
fn perimeter(&self) -> i32 {
self.a + self.b + self.c
}
}
fn total_perimeter(shapes: &Vec<Box<dyn Shape>>) -> i32 {
let mut total = 0;
for shape in shapes {
total += shape.perimeter();
}
total
}
fn largest_shape(shapes: &Vec<Box<dyn Shape>>) -> String {
let mut largest = &shapes[0];
for shape in shapes {
if shape.perimeter() > largest.perimeter() {
largest = shape;
}
}
largest.name()
}
Rust details worth knowing
- Borrowing the list. The functions take
&Vec<Box<dyn Shape>>, so they only look at the shapes, and the caller keeps its list. Looping withfor shape in shapesgives each element as a reference to a box. largestis a reference.let mut largest = &shapes[0]doesn't move the first box out of the list. It points at one of the shapes, and the assignmentlargest = shapemoves the pointer.- Strictly greater. Because the comparison is
>, a later shape with an equal perimeter doesn't replace the current one, so on a tie the shape that came first wins. - No return keyword.
totalandlargest.name()have no semicolon, so they are the values the functions return.
Complexity
Each function looks at every shape once and each method call takes constant time, so both run in O(n) time for n shapes and use no extra space.
Edge cases and common mistakes
- Ties. A rectangle 2 by 4, a square of side 3 and a triangle 4, 4, 4 all have perimeter 12. The first one, the rectangle, is the answer.
- A square-shaped rectangle. A 1 by 1 rectangle has the same sides as a square, but its
nameis still"Rectangle", because each struct answers for itself. - Checking the kind. Don't try to find out which struct a box holds. Call the trait's methods and let each one answer.
- Forgetting
mut.totalandlargestboth change inside the loop, so both needlet mut.
Adding a new kind of shape
The two functions never name a struct, so a new shape works with them without changing them. A hexagon, written in a file of your own next to the solution, is only a struct and an impl Shape for Hexagon block:
struct Hexagon {
side: i32,
}
impl Shape for Hexagon {
fn name(&self) -> String {
"Hexagon".to_string()
}
fn perimeter(&self) -> i32 {
6 * self.side
}
}
With a list of Square::new(5), Hexagon { side: 4 } and Triangle::new(3, 4, 5), both functions run unchanged and print:
56 Hexagon
The perimeters are 20, 24 and 12. This is the reason for the rule that the functions must work through the trait only: a chain of "if it is a rectangle ... else if it is a square ..." would need a new branch for every new shape, while the trait call needs none.
Testing
Building the three example lists and calling both functions prints:
46 Square
36 Rectangle
15 Triangle
In the last list, a square of side 1, a rectangle 1 by 1 and a triangle 2, 2, 3 have the perimeters 4, 4 and 7, and the triangle wins. Calling name() and perimeter() on those three shapes prints Square 4, Rectangle 4 and Triangle 7.
