keyword

Rust trait: define a shared behavior contract

A trait describes behavior that implementing types must provide. It can also include default implementations and associated items. Expected output (not executed): 250 Why: Ticket implements the required method, so the trait behavior is available. Common mistake: Declaring a trait does not automatically implement it for every type with a similarly named method.

Formal Syntax & Structure

rust syntaxrust
trait Name { fn method(&self) -> Type; }

Working Example

Example Snippetrust
trait Cost { fn cents(&self) -> u32; }struct Ticket;impl Cost for Ticket { fn cents(&self) -> u32 { 250 } }
fn main() {    println!("{}", Ticket.cents());}
Rust Reference