trait-concept
Rust Extension traits
An extension trait adds opt-in behavior to an existing type. In another module, the trait generally needs to be in scope for dot-call syntax. It does not modify the original type or its inherent implementation. Expected output (not executed): Ready! Why: The local trait is implemented for str, and the use statement makes it visible. Common mistake: Assuming every external user automatically has the trait in scope.
Formal Syntax & Structure
rust syntaxrust
trait Extension { fn extra(&self); }Working Example
Example Snippetrust
mod text { pub trait Exclaim { fn exclaim(&self) -> String; } impl Exclaim for str { fn exclaim(&self) -> String { format!("{self}!") } }}use text::Exclaim;fn main() { println!("{}", "Ready".exclaim()); }