trait-concept
Rust Borrowed trait objects
A borrowed trait object offers access to common behavior without taking ownership. The original owner must remain valid while the reference is used. Converting a concrete reference to a trait-object reference can occur at an expected-type coercion site. Expected output (not executed): meeting meeting Why: The trait-object reference borrows Memo rather than consuming it. Common mistake: Assuming &dyn Trait owns or extends the lifetime of the underlying value.
Formal Syntax & Structure
rust syntaxrust
&dyn TraitWorking Example
Example Snippetrust
trait Notice { fn message(&self) -> &str; }struct Memo(String);impl Notice for Memo { fn message(&self) -> &str { &self.0 } }fn main() { let memo = Memo(String::from("meeting")); let notice: &dyn Notice = &memo; println!("{}", notice.message()); println!("{}", memo.0);}