Rust trait objects
Trait object:
- a table of function pointers for each trait function, and a pointer to data
- size of object implementing the trait not known at compile time, because the concrete type is unknown. We don’t know how much space to allocate (in Rust terms:
dyn SomeTrait does not implement Sized)
- so:
- have to handle indirectly, via ref or pointer (e.g. Box)
- funcs in trait can’t return Self, or use Self in non-receiver argument
- can’t have generic function: allows infinite implementations, which with regular generics becomes finite at compile time, but in a dynamic trait object we can’t make it finite - we can’t generate the vtable, because we don’t know the concrete type.
You cannot use multiple non-auto traits for a trait object: you would need two pointers to two vtables. A workaround is to create a new trait with the two as bounds to combine vtables, then a blanket impl impl<T: Trait + Trait2> Trait3 for T {}, and use that in the trait object. Then you can add casting methods to get the other traits.
https://github.com/pretzelhammer/rust-blog/blob/master/posts/sizedness-in-rust.md