trait-concept

Rust Required trait methods

A trait can require a behavior without prescribing its implementation. Every implementation must supply the required method unless a default exists. This lets unrelated data types expose one common capability. Expected output (not executed): Lab Why: Room fulfills Named by defining the required method with the matching signature. Common mistake: Adding a method with the same name but an incompatible signature.

Formal Syntax & Structure

rust syntaxrust
trait Named { fn name(&self) -> &str; }

Working Example

Example Snippetrust
trait Named { fn name(&self) -> &str; }struct Room(&'static str);impl Named for Room {    fn name(&self) -> &str { self.0 }}fn main() { println!("{}", Room("Lab").name()); }
Rust Reference