You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Traits and generics are Rust's tools for abstraction and code reuse. Traits define shared behaviour (similar to interfaces), and generics allow you to write code that works with multiple types.
A trait defines a set of methods that a type must implement:
trait Summary {
fn summarise(&self) -> String;
}
struct NewsArticle {
title: String,
author: String,
content: String,
}
impl Summary for NewsArticle {
fn summarise(&self) -> String {
format!("{}, by {} — {}", self.title, self.author, &self.content[..50])
}
}
struct Tweet {
username: String,
content: String,
}
impl Summary for Tweet {
fn summarise(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
Traits can provide default method bodies:
trait Summary {
fn summarise_author(&self) -> String;
fn summarise(&self) -> String {
format!("(Read more from {}...)", self.summarise_author())
}
}
Types can override the default or use it as-is.
Accept any type that implements a trait:
fn notify(item: &impl Summary) {
println!("Breaking news: {}", item.summarise());
}
The equivalent, more explicit form:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.