Define a trait with required methods and use the impl keyword to provide those method bodies for a specific struct or type.
Implement a trait in Rust by defining the trait with required methods, then using the impl keyword to provide those methods for a specific type.
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
headline: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("Read more: {}...", self.headline)
}
}
A trait is like a contract that defines a set of actions a type must be able to perform. Implementing it means you are promising your specific data type can do those actions and then writing the code to make it happen. Think of it like a job description (the trait) and you writing the resume (the implementation) to prove you can do the job.