RRust By Example
intermediateTraits

Trait Default Implementation

Provide default behavior for trait methods.

Trait Default Implementation

Provide default behavior for trait methods.

Difficulty

Intermediate

Code

rust
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

This example demonstrates how to use trait default implementation in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

More Traits Examples