trait-concept
Rust Trait associated functions
An associated function has no receiver when it does not take self. A trait can define a construction contract for its implementing types without needing an existing instance. Expected output (not executed): 0 Why: Cart::empty chooses the Empty implementation for Cart. Common mistake: Calling a receiver-free associated function as if it were an instance method.
Formal Syntax & Structure
rust syntaxrust
trait Empty { fn empty() -> Self; }Working Example
Example Snippetrust
trait Empty { fn empty() -> Self; }struct Cart { items: u32 }impl Empty for Cart { fn empty() -> Self { Self { items: 0 } } }fn main() { println!("{}", Cart::empty().items); }