Sub topic 3
What dyn Trait means
This chapter assumes you can define traits and implement them for structs, and that you have used generic functions with trait bounds such as fn f<T: Shape>(x: T). You should also know what Box and & references are. The chapter explains dyn Trait as a type: what it names, why the compiler treats it as unsized, and what that means in practice.
A trait is not a type, but dyn Trait is
A trait such as Shape describes behavior. You cannot write let x: Shape = ..., because Shape is not a type. A type has a size and a layout, and a trait has neither.
Writing dyn Shape names a type: "some value whose concrete type implements Shape, and whose concrete type is not known here". This type is called a trait object type. A value of that kind is a trait object. The dyn keyword is required in the 2021 edition and later. Older code may write a bare Box<Shape>, which is now an error.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let s: &dyn Shape = &Square(2.0);
println!("{}", s.area());
}The variable s has type &dyn Shape. After the coercion from &Square, the compiler no longer tracks that the value is a Square. All that remains is the promise that it implements Shape, so only Shape methods can be called on it.
Why dyn Trait is unsized
Most types have a size known at compile time. i32 is 4 bytes, and Square is 8 bytes. Rust calls these sized types, and they implement the marker trait Sized automatically.
dyn Shape could stand for Square, for a Circle with a different size, or for a type defined in another crate. Its size depends on which concrete type is behind it, so it is a dynamically sized type (DST). Other DSTs are the slice [T] and str.
| Type | Sized? | How you normally hold it |
|---|---|---|
| `i32`, `Square` | Yes | By value, on the stack or in a field |
| `[i32]` | No | `&[i32]`, `Box<[i32]>` |
| `str` | No | `&str`, `Box<str>` |
| `dyn Shape` | No | `&dyn Shape`, `Box<dyn Shape>` |
The compiler needs to know a value's size for several things:
- Reserving stack space for a local variable.
- Passing a value as a function argument.
- Returning a value.
- Storing a value in a struct field or an array element.
An unsized type fails all of these checks. These lines are therefore rejected:
let s: dyn Shape = Square(2.0);is rejected because a local needs a known size.fn show(s: dyn Shape)is rejected because a by-value parameter needs a known size.Vec<dyn Shape>is rejected because the elements of a vector must have a fixed size.
The fix is to put the value behind a pointer. A pointer has a known size no matter what it points to. The next chapter covers the pointer forms (&dyn, Box<dyn>, Rc<dyn>, Arc<dyn>) in detail. For now, remember that dyn Trait appears almost only as the target of a pointer.
The size of the value versus the size of the type
Although dyn Shape has no fixed size, each particular value behind a pointer does. You can ask for it with std::mem::size_of_val, which works on unsized values:
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: &dyn Shape = &Square(1.0);
let b: &dyn Shape = &Rect { w: 2.0, h: 3.0 };
println!("{} {}", size_of_val(a), size_of_val(b)); // 8 16
}Both a and b have the same static type, &dyn Shape, yet the values behind them are 8 and 16 bytes. The program finds this size at runtime. Calling size_of::<dyn Shape>() does not compile, because the type has no single size to report.
Using dyn Trait with generics: the ?Sized bound
Every generic parameter T carries an implicit T: Sized bound. This is why fn f<T: Shape>(x: &T) accepts &Square but refuses &dyn Shape. The compiler would have to take T = dyn Shape, and dyn Shape is not Sized.
You can lift the restriction with ?Sized, which reads "may or may not be 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) -> f64 {
s.area()
}
fn main() {
let sq = Square(2.0);
let dynamic: &dyn Shape = &sq;
println!("{} {}", describe(&sq), describe(dynamic));
}The first call uses T = Square. The second uses T = dyn Shape, which works because the compiler treats dyn Shape as implementing Shape. Each trait object type implements its own trait automatically. Add ?Sized to a generic function only if you take T behind a reference or other pointer, as &T does here. A by-value T must stay sized.
Methods on the trait object type itself
Because dyn Shape is a real type, you can write an inherent impl block for it. These methods are available on any trait object of that type, and on nothing else:
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl dyn Shape {
fn describe(&self) -> String {
format!("area {:.1}", self.area())
}
}
fn main() {
let s: Box<dyn Shape> = Box::new(Square(3.0));
println!("{}", s.describe());
}Calling Square(3.0).describe() directly would not compile. describe belongs to dyn Shape, not to Square. The pattern is uncommon. You mostly meet it in libraries, for example the methods defined directly on dyn Any, which a later chapter uses.
What the compiler remembers
Coercing a &Square to &dyn Shape is a one-way unsizing coercion. The compiler erases the concrete type from the static type but keeps what it needs to call trait methods later. Three consequences follow.
- Only methods of the trait (and its supertraits) are callable. Fields and inherent methods of
Squareare not reachable through the trait object. - The compiler cannot recover
Squarewithout help. A later chapter covers downcasting withdyn Any. - The extra information the compiler keeps is stored in the pointer, not in the value. The pointer to a trait object is therefore larger than an ordinary pointer.
Common errors
- "the size for values of type
dyn Shapecannot be known at compilation time." You useddyn Shapeby value as a local, parameter, return type, or collection element. Put it behind&,Box,Rc, orArc. - "trait objects must include the
dynkeyword." You wrote a bare trait name where a type is expected. Adddyn. - A generic function rejects
&dyn Shape. The implicitT: Sizedbound is the cause. Add?Sizedto the parameter if the function only usesTbehind a pointer. - A method is not found on a trait object. It is probably an inherent method of the concrete type, or it belongs to a different trait that is not in the object's type.
Exercise
The line let s: dyn Shape = Square(2.0); fails to compile. Why does it fail, and what are two ways to change the declaration so that it compiles?
Show answer
The type dyn Shape is unsized, because the concrete type behind it could have any size, and a local variable must have a size known at compile time. Put the value behind a pointer: write let s: &dyn Shape = &Square(2.0); to borrow it, or let s: Box<dyn Shape> = Box::new(Square(2.0)); to own it on the heap. A third option is to drop the trait object and write let s = Square(2.0);, which keeps the concrete type.
Exercise
Why does fn describe<T: Shape>(s: &T) reject an argument of type &dyn Shape, and what single change makes it accept one?
Show answer
Every generic parameter has an implicit T: Sized bound. Accepting &dyn Shape requires T = dyn Shape, which is unsized, so the call fails. Change the bound to T: Shape + ?Sized. The parameter then accepts both sized types such as Square and the unsized dyn Shape.