Sub topic 4
Putting trait objects behind pointers
This chapter assumes you know basic ownership and borrowing, how to implement a trait for a struct, and how Box and references work. It also assumes you have seen the dyn Trait type from the previous chapter.
Why a pointer is required
dyn Trait is a dynamically sized type. The compiler cannot know its size, because the value behind it might be a Circle, a Rect, or any other implementor. Rust needs a known size for local variables, function arguments, and struct fields. So you never hold a bare dyn Trait. You hold it behind a pointer.
// Does not compile: the size of `dyn Greet` is not known at compile time.
// let g: dyn Greet = En;The pointer has a known size, and it points at the value. The next chapter covers how the pointer also carries the information needed to call methods.
The four common pointer forms
| Type | Ownership | Typical use |
|---|---|---|
| `&dyn Trait` / `&mut dyn Trait` | Borrowed | Function parameters that accept any implementor |
| `Box<dyn Trait>` | Single owner | Storing or returning one value of an unknown type |
| `Rc<dyn Trait>` | Shared, single thread | Several owners in one thread |
| `Arc<dyn Trait>` | Shared, thread-safe | Several owners across threads |
All four are built the same way. You create a pointer to a concrete type, and the compiler converts it to a pointer to dyn Trait. This conversion is called an unsized coercion. It happens when the expected type is known, such as in a let with a type annotation or a function argument.
Example
use std::rc::Rc;
use std::sync::Arc;
trait Greet {
fn hi(&self) -> String;
}
struct En;
struct Fr;
impl Greet for En {
fn hi(&self) -> String {
"hello".to_string()
}
}
impl Greet for Fr {
fn hi(&self) -> String {
"bonjour".to_string()
}
}
fn show(g: &dyn Greet) {
println!("{}", g.hi());
}
fn main() {
let en = En;
show(&en); // &En coerces to &dyn Greet
let boxed: Box<dyn Greet> = Box::new(Fr);
show(&*boxed); // reborrow the box contents as &dyn Greet
show(boxed.as_ref());
let shared: Rc<dyn Greet> = Rc::new(En);
let other = Rc::clone(&shared);
println!("{} {}", other.hi(), Rc::strong_count(&shared));
let arc: Arc<dyn Greet> = Arc::new(Fr);
println!("{}", arc.hi());
}This prints hello, bonjour, bonjour, hello 2, and bonjour, each on its own line.
Note that Rc::new(En) produces an Rc<En>. The annotation Rc<dyn Greet> on the binding makes the compiler coerce it. Cloning an Rc<dyn Greet> copies the pointer and increments the count. It does not copy the underlying value.
Common errors
- Missing the pointer. Writing
Vec<dyn Greet>orfn f() -> dyn Greetfails with "the size for values of typedyn Greetcannot be known at compilation time". Wrap the type inBox,&,Rc, orArc. - No annotation, no coercion.
let b = Box::new(Fr);gives aBox<Fr>. Add the typeBox<dyn Greet>or the compiler will not convert it. - Mixing up
Box<dyn T>and&dyn T. A function that takes&dyn Greetcannot take aBox<dyn Greet>directly. Pass&*boxedorboxed.as_ref(). - Moving out of a shared pointer.
Rc<dyn Trait>andArc<dyn Trait>only give you&selfaccess. You cannot call a method that takesselfby value on them.
Exercise
Why does let items: Vec<dyn Greet> = Vec::new(); fail to compile, and what is the smallest change that fixes it for a collection owning its elements?
Show answer
dyn Greet has no size known at compile time, but a Vec element type must be sized. Put the trait object behind a pointer: Vec<Box<dyn Greet>>. Use Vec<Rc<dyn Greet>> or Vec<Arc<dyn Greet>> if the elements need shared ownership.