Skip to content
Rust

Trait

Define and implement traits.

By EZ4Code Team
traitinterface

Code

// Define trait
trait Summary {
    fn summarize(&self) -> String;

    // Default method
    fn preview(&self) -> String {
        format!("{}...", &self.summarize()[..10])
    }
}

struct Article {
    title: String,
    content: String,
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{}: {}", self.title, self.content)
    }
}

// Trait as parameter
fn notify(item: &impl Summary) {
    println!("Breaking: {}", item.summarize());
}

// trait bound
fn notify_all<T: Summary>(item: &T) {
    println!("{}", item.summarize());
}

// Multiple trait bounds
fn display(item: &(impl Summary + std::fmt::Display)) {}

fn main() {
    let article = Article {
        title: "Rust".to_string(),
        content: "Learn Rust".to_string(),
    };
    println!("{}", article.summarize());
    println!("{}", article.preview());
    notify(&article);
}

Explanation

Traits define shared behavior, similar to interfaces, supporting default implementations and trait bound generic constraints.

More Rust Snippets