Define and implement traits
Quick answer
A trait describes shared behavior without requiring types to share the same fields. Implement it for each type that should provide that behavior.
A contract for behavior
Declare methods with trait Name { ... } and implement them with impl Name for Type. A trait method can have a default body using other methods from the same trait. Implementations must satisfy required method signatures.
trait Describe { fn describe(&self) -> &str; }struct Lamp;impl Describe for Lamp { fn describe(&self) -> &str { "lamp" } }fn main() { println!("{}", Lamp.describe()); }Expected stdout (not executed):
lampThe implementation supplies the required method.
trait Price { fn cents(&self) -> u32; fn free(&self) -> bool { self.cents() == 0 }}struct Sample;impl Price for Sample { fn cents(&self) -> u32 { 0 } }fn main() { println!("{}", Sample.free()); }Expected stdout (not executed):
trueThe default method calls the type's implementation.
Common mistake
A trait is not a struct; it describes behavior rather than storing fields.
Try it yourself
Define a trait for a reading in degrees and implement it for two sensor models.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Define and implement traits — practice quiz
Choose one answer per question, then review the explanation.
Which syntax implements trait Named for type Item?
Can a default trait method call another required method on self?
An impl omits a required trait method without a default. What happens?