Sub topic 11
Making a Trait Usable with where Self: Sized
This chapter assumes you know how to define and implement traits and write generic functions with bounds. It also assumes you have used Box<dyn Trait> and understand that dyn Trait is an unsized type. The previous chapter listed the rules that decide whether a trait is dyn compatible. This chapter covers the main tool for working within those rules: the where Self: Sized bound on a single method.
The problem: one method can disqualify a whole trait
Dyn compatibility is checked for the trait as a whole. Suppose you write a trait with a useful get method and add a convenience method get_as<T> that parses the result into any type. The get_as method is generic over T. A vtable is a fixed table of function pointers, and one generic method would need a separate entry for every T. The compiler can't build such a table, so the trait stops being dyn compatible. Writing Box<dyn Store> then fails with error E0038, which says the trait cannot be made into an object.
You don't want to give up the convenience method, and you don't want to give up dyn Store. The fix is to tell the compiler that get_as only needs to work when the concrete type is known.
The fix: a Sized bound on the method
trait Store {
fn get(&self, key: &str) -> Option<String>;
// A generic method would make the trait not dyn compatible,
// so it is excluded from the vtable with `where Self: Sized`.
fn get_as<T: std::str::FromStr>(&self, key: &str) -> Option<T>
where
Self: Sized,
{
self.get(key)?.parse().ok()
}
}
struct Mem;
impl Store for Mem {
fn get(&self, key: &str) -> Option<String> {
Some(key.len().to_string())
}
}
fn main() {
let concrete = Mem;
let n: Option<u32> = concrete.get_as("abc");
println!("{:?}", n);
let dynamic: Box<dyn Store> = Box::new(Mem);
println!("{:?}", dynamic.get("abcd"));
}This prints Some(3) and then Some("4").
The bound where Self: Sized means this method exists only for implementing types whose size is known at compile time. Two things follow:
- The compiler skips the method when it checks dyn compatibility and when it builds the vtable.
Storeis now dyn compatible. dyn Storeis notSized, so the method cannot be called on a trait object. Callingdynamic.get_as::<u32>("abc")fails with an error saying the method cannot be invoked on a trait object.
What the decision looks like
What the bound can fix
The bound works on any method that would otherwise break the rules:
| Method feature | Dyn compatible without the bound? | With `where Self: Sized` |
|---|---|---|
| Generic type parameter, including `impl Trait` arguments | No | Allowed, not callable on `dyn` |
| Returns `Self` by value | No | Allowed, not callable on `dyn` |
| Takes another `Self` as an argument | No | Allowed, not callable on `dyn` |
| No `self` receiver, such as `fn new() -> Self` | No | Allowed, not callable on `dyn` |
| Only lifetime parameters | Yes | Not needed |
| Ordinary `&self` or `&mut self` method | Yes | Not needed |
Constructors are the most common case. This trait has unit, which has no receiver and returns Self:
trait Shape {
fn area(&self) -> f64;
fn unit() -> Self
where
Self: Sized;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
fn unit() -> Self {
Square(1.0)
}
}
fn main() {
let s = Square::unit();
let boxed: Box<dyn Shape> = Box::new(s);
println!("{}", boxed.area());
}This prints 1. You build values through the concrete type, then erase the type when you store them.
The standard library does this everywhere
Iterator has dozens of methods, including map, filter, zip, and collect. They are generic or consume self, so each one carries where Self: Sized. Only next and a few others stay in the vtable, and that is why dyn Iterator exists at all.
You can still use the adapters on a boxed iterator, because Box<dyn Iterator> is itself a sized type that implements Iterator:
fn main() {
let it: Box<dyn Iterator<Item = u32>> = Box::new(vec![1, 2, 3].into_iter());
let doubled: Vec<u32> = it.map(|x| x * 2).collect();
println!("{:?}", doubled);
}This prints [2, 4, 6]. The adapter is called on the Box, which is Sized, not on the unsized dyn Iterator inside it. The standard library provides this kind of forwarding implementation for Box<I> where I: Iterator + ?Sized.
Gotchas
A Sized supertrait is a different thing
Writing the bound on a method excludes that method. Writing it on the trait excludes everything:
trait Store: Sizedmeans every implementor must be sized, sodyn Storecan never exist.- The same happens if a supertrait requires
Sized.trait Shape: Cloneis not dyn compatible becauseCloneitself requiresSized.
The method must be callable when the caller has only dyn
Adding the bound is not free. If your API's users hold Box<dyn Store>, they cannot call get_as. Check whether the excluded method is something dyn users need before you rely on the bound. If it is, you have two options.
- Give the dyn-friendly version a different shape. For example,
fn get_str(&self, key: &str) -> Option<String>is not generic and stays in the vtable. - Move the generic method into an extension trait with a blanket implementation that allows unsized types.
The second option looks like this:
use std::str::FromStr;
trait Store {
fn get(&self, key: &str) -> Option<String>;
}
trait StoreExt: Store {
fn get_as<T: FromStr>(&self, key: &str) -> Option<T> {
self.get(key)?.parse().ok()
}
}
// `?Sized` lets the blanket impl cover `dyn Store` as well.
impl<S: Store + ?Sized> StoreExt for S {}
struct Mem;
impl Store for Mem {
fn get(&self, key: &str) -> Option<String> {
Some(key.len().to_string())
}
}
fn main() {
let dynamic: Box<dyn Store> = Box::new(Mem);
let n: Option<u32> = dynamic.get_as("abcd");
println!("{:?}", n);
}This prints Some(4). The generic method now lives in a separate trait, so it never enters the Store vtable. The extension trait is generic code that the compiler monomorphizes for dyn Store itself, and it only calls get through the vtable.
Returning Self has a dyn-friendly counterpart
A clone-like method can't return Self on a trait object, because the caller doesn't know the size of the result. The usual workaround is a method that returns a box, such as fn clone_box(&self) -> Box<dyn Shape>. That method has no Sized bound and stays in the vtable. The concrete type implements it by boxing a clone of itself.
Implementors can still override the method
Default bodies and overrides work normally. An implementing type can override a where Self: Sized method. The override is also unavailable through dyn, so it won't be reached through a trait object.
Summary of the rule
Put where Self: Sized on a method when the method:
- needs generics,
Selfby value, or has no receiver, and - is only needed by code that knows the concrete type.
Leave it off every method that dyn callers need. If a trait has no such methods at all, you don't need the bound, and the trait is already dyn compatible.
Exercise
A trait has the method fn duplicate(&self) -> Self;. A colleague wants to store implementors as Vec<Box<dyn Trait>>. Which change keeps the trait dyn compatible, and what can't callers do afterwards?
Show answer
Add where Self: Sized to duplicate. The trait becomes dyn compatible because the method is left out of the vtable. Code holding a Box<dyn Trait> can no longer call duplicate. Only code that knows the concrete type can. If dyn users need duplication, add a separate method like fn duplicate_box(&self) -> Box<dyn Trait> that stays in the vtable.
Exercise
What is the difference between trait Store { fn get_as<T>(&self) -> T where Self: Sized; } and trait Store: Sized { fn get_as<T>(&self) -> T; } when you want to write Box<dyn Store>?
Show answer
The first is dyn compatible. The bound applies to one method, so only that method is excluded from the vtable. The second is not dyn compatible, because the Sized supertrait applies to the whole trait and dyn Store is unsized. Box<dyn Store> is rejected with E0038.