Skip to content
Rust

Trait

trait 정의 및 구현.

#trait#interface

Code

rust
// 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);
}