Trait Basic
Define and implement traits for custom types.
Trait Basic
Define and implement traits for custom types.
Difficulty
Intermediate
Code
trait Summary {
fn summarize(&self) -> String;
}
struct Article {
title: String,
author: String,
}
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {}", self.title, self.author)
}
}
fn main() {
let article = Article {
title: String::from("Rust is Great"),
author: String::from("Ferris"),
};
println!("{}", article.summarize());
}Explanation
Traits define shared behavior. impl Trait for Type provides implementation.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the traits category to build a complete understanding of this topic.