intermediateTraits
Trait Basic
Define and implement traits for custom types.
Trait Basic
Define and implement traits for custom types.
Difficulty
Intermediate
Code
rust
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
This example demonstrates how to use trait basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the traits category to build a complete understanding of this topic.