trait-concept

Rust Default trait methods

A default method provides reusable behavior. A type may use the default or override it with its own implementation, while still following the trait contract. Expected output (not executed): Item: Book Why: The default label calls the required name method implemented by Book. Common mistake: Assuming a default method removes the need to implement other required methods.

Formal Syntax & Structure

rust syntaxrust
trait Named { fn name(&self) -> &str; fn label(&self) -> String { /* body */ } }

Working Example

Example Snippetrust
trait Named {    fn name(&self) -> &str;    fn label(&self) -> String { format!("Item: {}", self.name()) }}struct Book;impl Named for Book { fn name(&self) -> &str { "Book" } }fn main() { println!("{}", Book.label()); }
Rust Reference