Activity 29: Traits
We did Problems 1 to 3 together in lecture, on the handout. Problem 4 was the laptop part, handed in on Gradescope.
Problem 1: implement a trait (in lecture)
Describe and print_card are the ones from the slides:
trait Describe {
fn describe(&self) -> String;
}
fn print_card(item: &impl Describe) {
println!("{}", item.describe());
}
Write the impl block so that this program prints a 20-sided die.
struct Die { sides: u32 }
// your impl here
fn main() {
let d20 = Die { sides: 20 };
print_card(&d20);
}
Answer.
impl Describe for Die {
fn describe(&self) -> String {
format!("a {}-sided die", self.sides)
}
}
Problem 2: default methods (in lecture)
trait Scorer {
fn points(&self) -> u32;
fn label(&self) -> String {
format!("{} points", self.points())
}
}
struct Touchdown;
struct FieldGoal;
impl Scorer for Touchdown {
fn points(&self) -> u32 { 6 }
}
impl Scorer for FieldGoal {
fn points(&self) -> u32 { 3 }
fn label(&self) -> String { String::from("three, kicked") }
}
fn main() {
println!("{}", Touchdown.label());
println!("{}", FieldGoal.label());
}
- What are the two lines this prints?
- Add a
Safety, worth 2 points, that uses the default label. Write the struct and itsimpl.
Answer. It prints 6 points, then three, kicked. Touchdown never wrote label, so it gets the default from the trait.
struct Safety;
impl Scorer for Safety {
fn points(&self) -> u32 { 2 }
}
Problem 3: implement Ord (in lecture)
sort needs Ord, and Ord is one method:
trait Ord {
fn cmp(&self, other: &Self) -> Ordering;
}
enum Ordering { Less, Equal, Greater }
Write impl Ord for Striker so that strikers.sort() puts the fewest goals first. u32 already knows how to cmp, so 7.cmp(&12) is Ordering::Less.
Ord needs Eq too, which is like PartialEq but also needs every value to equal itself. That's the extra word in the derive line.
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
struct Striker { name: String, goals: u32 }
// your impl Ord here
// Rust also wants PartialOrd. It just asks Ord:
impl PartialOrd for Striker {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
If you have time: what one change puts the most goals first?
Answer.
impl Ord for Striker {
fn cmp(&self, other: &Self) -> Ordering {
self.goals.cmp(&other.goals)
}
}
The body hands the job to u32's own cmp. Writing it out with if self.goals < other.goals { Ordering::Less } ... works too. For most goals first, swap the two sides: other.goals.cmp(&self.goals).
Problem 4: shapes (on a laptop)
The starting file is at tinyurl.com/210shape, with these steps as comments at the top. It compiles as is, and panics at the first todo!().
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
fn describe(&self) -> String {
format!("{} with area {:.1}", self.name(), self.area())
}
}
struct Rectangle { width: f64, height: f64 }
struct Circle { radius: f64 }
impl Shape for Rectangle {
fn area(&self) -> f64 { todo!() }
fn name(&self) -> String { todo!() }
}
impl Shape for Circle {
fn area(&self) -> f64 { todo!() }
fn name(&self) -> String { todo!() }
}
fn main() {
let rect = Rectangle { width: 5.0, height: 3.0 };
let circle = Circle { radius: 2.0 };
println!("{}", rect.describe());
println!("{}", circle.describe());
}
Step 1. Fill in the four todo!()s. A rectangle's area is width times height; a circle's is PI times the radius squared. Run it. You should see rectangle with area 15.0 and circle with area 12.6.
Neither impl mentions describe. Where did it come from?
Step 2. Replace main with one that puts both shapes, plus a Rectangle { width: 2.0, height: 2.0 }, into a single vector, then loops over it printing describe() for each:
let shapes: Vec<Box<dyn Shape>> = vec![
// the three shapes, each inside Box::new(...)
];
for shape in &shapes {
// print each description
}
Try Vec<Shape> first, so you've seen the error. Then fix it.
Step 3. Add a third kind of shape: struct Triangle { base: f64, height: f64 }, with area half the base times the height. Write its impl Shape and add a Triangle { base: 6.0, height: 4.0 } to the vector. What did you have to change in the loop?
On Gradescope: your impl Shape for Circle, what your program prints, and one sentence on why the vector can't be Vec<Shape>.
Answer. After all three steps:
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
fn describe(&self) -> String {
format!("{} with area {:.1}", self.name(), self.area())
}
}
struct Rectangle { width: f64, height: f64 }
struct Circle { radius: f64 }
struct Triangle { base: f64, height: f64 }
impl Shape for Rectangle {
fn area(&self) -> f64 { self.width * self.height }
fn name(&self) -> String { String::from("rectangle") }
}
impl Shape for Circle {
fn area(&self) -> f64 { PI * self.radius * self.radius }
fn name(&self) -> String { String::from("circle") }
}
impl Shape for Triangle {
fn area(&self) -> f64 { 0.5 * self.base * self.height }
fn name(&self) -> String { String::from("triangle") }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Rectangle { width: 5.0, height: 3.0 }),
Box::new(Circle { radius: 2.0 }),
Box::new(Rectangle { width: 2.0, height: 2.0 }),
Box::new(Triangle { base: 6.0, height: 4.0 }),
];
for shape in &shapes {
println!("{}", shape.describe());
}
}
It prints rectangle with area 15.0, circle with area 12.6, rectangle with area 4.0, triangle with area 12.0. Neither impl wrote describe, they used the trait's default method. Adding the triangle changed nothing in the loop, because the loop only asks for a Shape.
The vector can't be a Vec<Shape> because Shape is a trait, a promise about types, and a Vec needs one type with one size. A Box<dyn Shape> is a pointer, which has a size.
Challenge: Display by hand
Implement Display for Rectangle so that println!("{}", rect) prints 5 x 3. You'll need use std::fmt; and an impl fmt::Display for Rectangle with one fmt method, like the Suit example from lecture.
Answer.
use std::fmt;
impl fmt::Display for Rectangle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} x {}", self.width, self.height)
}
}