Traits & GenericsBeginner
1Question 1 of 1
rustHow do Traits and Generics provide polymorphism in Rust?
Explanation & Concept
Traits in Rust define shared behavior across types (similar to interfaces in other languages).
• Generics with Trait Bounds provide **static dispatch** via monomorphization (zero runtime cost). • Trait Objects (`dyn Trait`) provide **dynamic dispatch** via vtables when heterogeneous types are stored together.
Code Example
rust
pub trait Summarizable {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
}
impl Summarizable for NewsArticle {
fn summarize(&self) -> String {
format!("Breaking: {}", self.headline)
}
}
// Static dispatch with trait bound
pub fn notify<T: Summarizable>(item: &T) {
println!("{}", item.summarize());
}How It Works & Key Takeaways
Monomorphization compiles specialized native machine code for each concrete type used with generic functions, delivering maximum runtime speed.
Mock Test · 1 Questions · Optional
Ready for Pattern Matching?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions