Sub topic 11
Making a trait usable with where Self: Sized
This chapter assumes you know the dyn compatibility rules from the previous chapter: a trait with generic methods, or with methods that return Self or have no receiver, cannot be used as dyn Trait. Here you will see how to keep such methods without giving up trait objects.
The problem
A vtable holds one function pointer per method. A generic method such as get_as<T> would need one pointer for every possible T, so the compiler cannot build the table. By default, one such method makes the whole trait not dyn compatible.
The opt-out
Adding where Self: Sized to a method removes it from the vtable. The method can then only be called when the compiler knows the concrete type. A dyn Trait is unsized, so it never satisfies the bound.
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 call concrete.get_as("abc") works because Mem is sized. The trait object dynamic can call get, which is in the vtable. If you wrote dynamic.get_as::<u32>("abcd"), the compiler would reject it because dyn Store does not satisfy Self: Sized.
What else it fixes
The same bound works for any method that breaks dyn compatibility:
- Generic methods with type parameters.
- Associated functions with no
selfreceiver, such as constructors likefn new() -> Self. - Methods that return
Selfby value, or takeselfby value in a way that needs the concrete size.
Provided methods that use Self: Sized often act as convenience helpers. The standard library does this with Iterator. Methods such as map and filter carry where Self: Sized, so Box<dyn Iterator<Item = u32>> is a valid type.
Trait-level bound versus method-level bound
Do not confuse the two placements.
| Placement | Effect |
|---|---|
| `trait Foo: Sized` | Every implementor must be sized. The trait is **not** dyn compatible. |
| `fn bar(&self) where Self: Sized` | Only `bar` is excluded from the vtable. The trait stays dyn compatible. |
Common errors
- Putting
Sizedon the trait itself. The error says the trait cannot be made into an object. Move the bound to the offending method. - Forgetting that the method body still needs a default. A method with
where Self: Sizedand no default must still be implemented by every type, as usual. - Calling the method through a
&dyn Traitand expecting auto-dereferencing to help. It does not, becauseSelfisdyn Trait.
Exercise
A trait has fn parse_all<T: FromStr>(&self) -> Vec<T>; and you want to store implementors as Box<dyn Reader>. What is the smallest change that makes the trait dyn compatible, and what do you lose?
Show answer
Add where Self: Sized to parse_all. The trait can then be used as dyn Reader, but parse_all can only be called on concrete types, not on Box<dyn Reader>. Because the method is generic and has no default body, every implementor must still provide it.