Rust

Trait with Default Methods

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A trait can supply default implementations — implementors override only the bits they need. Like abstract base classes, but with structural typing and zero runtime cost.
Rust
Raw
trait Greeter {
    fn name(&self) -> &str;

    // Default — only `name` must be implemented.
    fn greet(&self) -> String {
        format!("Hello, {}!", self.name())
    }

    fn shout(&self) -> String {
        self.greet().to_uppercase()
    }
}

struct Person { name: String }

impl Greeter for Person {
    fn name(&self) -> &str { &self.name }
    // Override only if you want different behavior
    fn greet(&self) -> String { format!("Howdy, {}!", self.name) }
}

fn main() {
    let p = Person { name: "Alice".into() };
    println!("{}", p.greet());      // Howdy, Alice!     (overridden)
    println!("{}", p.shout());      // HOWDY, ALICE!    (uses default)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.