Sub topic 4
Putting trait objects behind pointers
This chapter covers the pointer types that can hold a dyn Trait value: &dyn, &mut dyn, Box<dyn>, Rc<dyn>, and Arc<dyn>. It assumes you know basic ownership and borrowing, how to implement a trait for a struct, and how Box and references work. The previous chapter showed that dyn Trait is a type whose size is not known at compile time. This chapter shows how to hold such a value anyway.
Why a pointer is required
A local variable, a function parameter, or a struct field needs a size known at compile time. dyn Shape could be a Circle (8 bytes) or a Rect (16 bytes), so the compiler cannot give it a fixed size. Types like this are called dynamically sized types (DSTs). The compiler refuses to place them directly on the stack or in a field.
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
r: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
}
fn main() {
let c = Circle { r: 1.0 };
// let s: dyn Shape = c; // error: the size for values of type `dyn Shape` cannot be known
let s: &dyn Shape = &c; // fine: a reference has a known size
println!("{:.2}", s.area());
}A pointer to a DST has a known size, so the pointer can live anywhere a value can. The value it points to sits elsewhere: on the stack, on the heap, or inside another allocation.
The four common pointer forms
Each pointer form gives a different ownership model. The trait object behaves the same way behind each one. Only who owns the data and who may use it changes.
| Pointer type | Owns the value? | Shared? | Typical use |
|---|---|---|---|
| `&dyn Trait` | No, it borrows | Many readers | Function parameters that only read |
| `&mut dyn Trait` | No, it borrows | One writer | Function parameters that mutate |
| `Box<dyn Trait>` | Yes | No | Collections, struct fields, return values |
| `Rc<dyn Trait>` | Yes, shared count | Single thread | Shared ownership without threads |
| `Arc<dyn Trait>` | Yes, shared count | Across threads | Shared ownership with threads |
Borrowed trait objects
&dyn Trait is the cheapest form because it allocates nothing. The caller keeps ownership, and the function sees only the trait's methods.
trait Counter {
fn bump(&mut self);
fn value(&self) -> u32;
}
struct Simple(u32);
impl Counter for Simple {
fn bump(&mut self) {
self.0 += 1;
}
fn value(&self) -> u32 {
self.0
}
}
fn bump_twice(c: &mut dyn Counter) {
c.bump();
c.bump();
}
fn show(c: &dyn Counter) {
println!("value = {}", c.value());
}
fn main() {
let mut s = Simple(0);
bump_twice(&mut s);
show(&s);
}The program prints value = 2. Rust converts &mut Simple to &mut dyn Counter automatically at the call site. This conversion is called an unsizing coercion.
Owned trait objects with Box
Box<dyn Trait> puts the value on the heap and owns it. Dropping the box drops the concrete value, using the right destructor for the real type. Use it when the value must outlive the scope that created it, or when it must be stored in a struct or returned.
trait Greeter {
fn greet(&self) -> String;
}
struct English;
struct French;
impl Greeter for English {
fn greet(&self) -> String {
String::from("hello")
}
}
impl Greeter for French {
fn greet(&self) -> String {
String::from("bonjour")
}
}
fn pick(lang: &str) -> Box<dyn Greeter> {
match lang {
"fr" => Box::new(French),
_ => Box::new(English),
}
}
fn main() {
println!("{}", pick("fr").greet());
println!("{}", pick("en").greet());
}The two match arms return different concrete types, yet both arms have the type Box<dyn Greeter>. This is something impl Greeter as a return type cannot do, because impl Trait stands for exactly one hidden concrete type.
Shared ownership with Rc and Arc
Rc<dyn Trait> and Arc<dyn Trait> keep a reference count. Cloning the pointer copies the pointer and increments the count. It does not copy the value.
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
trait Logger: Send + Sync {
fn log(&self, msg: &str);
}
struct Stdout;
impl Logger for Stdout {
fn log(&self, msg: &str) {
println!("log: {}", msg);
}
}
fn main() {
let local: Rc<dyn Logger> = Rc::new(Stdout);
let other = Rc::clone(&local);
other.log("from rc");
println!("rc count = {}", Rc::strong_count(&local));
let shared: Arc<dyn Logger> = Arc::new(Stdout);
let for_thread = Arc::clone(&shared);
let handle = thread::spawn(move || for_thread.log("from thread"));
handle.join().unwrap();
shared.log("from main");
}Rc is not thread-safe, and the compiler stops you from sending it to another thread. Use Arc when threads are involved. Sending an Arc<dyn Logger> also requires the trait object itself to be Send + Sync. Here the supertraits Send + Sync on Logger guarantee that. A later chapter covers this in detail.
Where the coercion happens
Rust turns a pointer to a concrete type into a pointer to a trait object at specific points called coercion sites. These include let statements with a type annotation, function arguments, struct fields, and return values.
A common error is relying on inference where no site exists. This fails:
trait Shape {
fn area(&self) -> f64;
}
struct Sq(f64);
impl Shape for Sq {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
// Without the annotation, `b` would be Box<Sq>, not Box<dyn Shape>.
let b: Box<dyn Shape> = Box::new(Sq(2.0));
println!("{}", b.area());
}Without : Box<dyn Shape>, the variable b has type Box<Sq>. A Vec built from several different boxed types then fails to compile, because the elements are not all the same type. Writing the annotation, or the Vec<Box<dyn Shape>> type, tells the compiler where to coerce.
What the pointer holds
A pointer to a sized type holds one address. A pointer to a trait object holds two: the address of the data and the address of a table of function pointers for the concrete type. The next chapter explains that table. For now, note that these pointers are twice as big.
use std::fmt::Debug;
use std::mem::size_of;
fn main() {
println!("{}", size_of::<&u8>()); // 8 on a 64-bit target
println!("{}", size_of::<&dyn Debug>()); // 16
println!("{}", size_of::<Box<dyn Debug>>()); // 16
println!("{}", size_of::<Rc<dyn Debug>>()); // 16
}
use std::rc::Rc;All four lines hold on a 64-bit target. The extra word is the cost of not knowing the concrete type, and it appears in every pointer form.
Common errors
- Forgetting the pointer.
Vec<dyn Shape>andfn f(s: dyn Shape)do not compile. UseVec<Box<dyn Shape>>andfn f(s: &dyn Shape). - Mixing
Rcand threads.Rc<dyn Trait>cannot cross a thread boundary. Switch toArc<dyn Trait>and addSend + Syncbounds. - Mutating through shared pointers.
Rc<dyn Trait>andArc<dyn Trait>give only&selfaccess. For&mut selfmethods, wrap the value, for exampleRc<RefCell<dyn Trait>>orArc<Mutex<dyn Trait>>. - Expecting
Clone.Box<dyn Trait>is notClone, becauseCloneneeds a sizedSelf. Cloning anRcorArcworks because it clones the pointer, not the value.
Exercise
You write fn make() -> impl Shape and return Circle { r: 1.0 } in one branch and Rect { w: 1.0, h: 2.0 } in the other. The code does not compile. What return type fixes it, and what does the function then have to do to its return values?
Show answer
Change the return type to Box<dyn Shape> and wrap each return value with Box::new(...). impl Shape names one hidden concrete type, so two branches with different types are rejected. Box<dyn Shape> is a single type, and each Box<Circle> or Box<Rect> coerces to it at the return site.
Exercise
A Vec<Box<dyn Shape>> holds 1,000 shapes. How many bytes do the pointers in the vector's buffer occupy on a 64-bit target, and why is it not 8,000?
Show answer
16,000 bytes. Each Box<dyn Shape> is a fat pointer holding a data pointer (8 bytes) and a vtable pointer (8 bytes). The shapes' own data lives in separate heap allocations and is not counted here.