Trait Default Implementation
Provide default behavior for trait methods.
Trait Default Implementation
Provide default behavior for trait methods.
Difficulty
Intermediate
Code
trait Greet {
fn name(&self) -> &str;
fn greet(&self) {
println!("Hello, I'm {}!", self.name());
}
}
struct Cat { name: String }
impl Greet for Cat {
fn name(&self) -> &str { &self.name }
}
fn main() {
let cat = Cat { name: String::from("Whiskers") };
cat.greet();
}Explanation
Traits can have default method implementations.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the traits category to build a complete understanding of this topic.