rust / expert
Snippet
Object Safety and Vtable Constraints
Not all traits can be used as dynamic trait objects (dyn Trait). For a trait to be 'object-safe', it cannot have generic methods or return 'Self' by value. However, you can keep a trait object-safe by adding a 'where Self: Sized' bound to specific methods, which excludes them from the vtable and prevents them from being called on dynamic objects.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
trait AdvancedPlugin {fn execute(&self);// This method makes the trait NOT object-safe if called on a Trait Objectfn generic_helper<T>(&self, _data: T) where Self: Sized;}fn run_plugins(plugins: &[Box<dyn AdvancedPlugin>]) {for p in plugins {p.execute();// p.generic_helper(42); // Error: cannot call generic method on dyn trait}}
Breakdown
1
dyn AdvancedPlugin
Represents a trait object using dynamic dispatch via a vtable.
2
where Self: Sized
A bound that prevents this method from being included in the dynamic dispatch vtable.
3
Box<dyn AdvancedPlugin>
Heap-allocated pointer to a type implementing the trait, required for heterogeneous collections.