Sub topic 3
What dyn Trait means
This chapter assumes you can define structs, implement traits, write generic functions with trait bounds, and use Box and references. It covers what the type dyn Trait is and why it behaves differently from other types. Pointers to it and the vtable come in later chapters.
A trait as a type
A trait bound such as T: Shape is a constraint on a type you already have. dyn Shape is different. It is a type in its own right, the type of "some value whose concrete type implements Shape, decided at runtime".
use std::mem::size_of_val;
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Rect {
w: f64,
h: f64,
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
fn main() {
let a: Box<dyn Shape> = Box::new(Square(2.0));
let b: Box<dyn Shape> = Box::new(Rect { w: 2.0, h: 3.0 });
println!("{} {}", a.area(), b.area());
println!("{} {}", size_of_val(&*a), size_of_val(&*b));
}This prints 4 6 and then 8 16. Both boxes have the same type, Box<dyn Shape>. The values they point to have different sizes.
Why dyn Trait is unsized
Every local variable and function argument needs a size known at compile time. dyn Shape has no fixed size, because Square takes 8 bytes and Rect takes 16. The type is therefore dynamically sized, written !Sized. Types such as str and [T] are also unsized.
Three consequences follow:
- You cannot write
let s: dyn Shape = Square(2.0);. The compiler reports that the size ofdyn Shapecannot be known at compile time. - You cannot take
dyn Shapeby value as a parameter or return it from a function. - You cannot call
size_of::<dyn Shape>(). Usesize_of_valon a reference instead, as the example does.
The fix is to keep the value behind a pointer, whose size is known. The next chapter covers those pointer forms.
Syntax and what the type implements
Since edition 2021, writing the bare trait name as a type, such as Box<Shape>, is a hard error. You must write dyn.
The compiler automatically implements Shape for dyn Shape. That is why a.area() works on the boxed value. A generic function with T: Shape accepts dyn Shape only if you relax the implicit Sized bound with T: Shape + ?Sized.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn describe<T: Shape + ?Sized>(s: &T) -> String {
format!("area {}", s.area())
}
fn main() {
let sq = Square(3.0);
let dynamic: &dyn Shape = &sq;
println!("{}", describe(&sq));
println!("{}", describe(dynamic));
}This prints area 9 twice. Without ?Sized, the second call fails to compile.
Common mistakes
- Writing
fn f(s: dyn Shape)instead of&dyn ShapeorBox<dyn Shape>. - Omitting
dynin edition 2021 or later. - Assuming
dyn Shapeis the same asimpl Shape. Withimpl Shapethe compiler knows one concrete type. Withdyn Shapeit does not.
Exercise
Why does let s: dyn Shape = Square(2.0); fail to compile, even though Square implements Shape?
Show answer
dyn Shape is an unsized type, because values of different implementing types have different sizes. A local variable must have a size known at compile time, so the value must sit behind a pointer such as &dyn Shape or Box<dyn Shape>.
Exercise
What must you add to fn describe<T: Shape>(s: &T) so it also accepts a &dyn Shape argument?
Show answer
Relax the implicit Sized bound by writing T: Shape + ?Sized.