trait-concept

Rust Dyn compatibility (object safety)

Not every trait can be used as dyn Trait. Its supertraits must also be dyn-compatible; it cannot require Self: Sized or expose associated constants, and object-dispatchable methods must satisfy restrictions on receivers, type parameters and uses of Self. Some otherwise incompatible methods can be excluded with where Self: Sized. Expected output (not executed): working Why: new is restricted to sized concrete implementors and is not callable through the object. Common mistake: Assuming a generic method can be called through dyn Trait just because the trait is implemented.

Formal Syntax & Structure

rust syntaxrust
trait Service { fn run(&self); }

Working Example

Example Snippetrust
trait Service {    fn run(&self) -> &str;    fn new() -> Self where Self: Sized;}struct Worker;impl Service for Worker {    fn run(&self) -> &str { "working" }    fn new() -> Self { Worker }}fn main() {    let worker = Worker::new();    let service: &dyn Service = &worker;    println!("{}", service.run());}
Rust Reference