Sub topic 1
Rust Traits: Defining Shared Behavior
Prerequisites
Assume you know Rust structs, ownership, borrowing, references, basic generics, and how to run a Cargo program. Traits build on these ideas by describing behavior without choosing one concrete type.
Defining and Implementing a Trait
A trait is a named set of methods that a type promises to provide. Define the required behavior with trait, then connect a type to it with impl Trait for Type.
trait Summary {
fn author(&self) -> &str;
fn summarize(&self) -> String {
format!("Read more from {}...", self.author())
}
}
struct Post {
author: String,
}
struct Tweet {
handle: String,
}
impl Summary for Post {
fn author(&self) -> &str {
&self.author
}
}
impl Summary for Tweet {
fn author(&self) -> &str {
&self.handle
}
fn summarize(&self) -> String {
format!("New tweet by @{}", self.author())
}
}
fn print_summary(item: &impl Summary) {
println!("{}", item.summarize());
}
fn main() {
let post = Post { author: String::from("Ana") };
let tweet = Tweet { handle: String::from("rustlang") };
print_summary(&post);
print_summary(&tweet);
}Post uses the default summarize method. Tweet overrides it because tweets need different wording. A default method can call required methods, so each implementation supplies only the type-specific part.
Constraining Generics with Trait Bounds
A trait bound restricts a generic type to values supporting specific behavior. The show function accepts any type that implements Summary:
fn show<T: Summary>(item: &T) {
println!("{}", item.summarize());
}Multiple bounds use +, such as T: Summary + Clone. A where clause makes longer bounds easier to read:
fn show<T>(item: &T)
where
T: Summary,
{
println!("{}", item.summarize());
}These constraints are checked at compile time. Calling show with a type that lacks Summary produces a compiler error.
Using `impl Trait`
For a simple argument bound, &impl Summary is shorter than &T with a separate generic declaration. Both forms accept one concrete type per call.
In a return position, impl Trait hides the concrete type while preserving static checking:
fn sample() -> impl Summary {
Post { author: String::from("Mira") }
}The function must always return the same concrete type, even though callers see only the Summary behavior.
Exercise
Why can sample not return either a Post or a Tweet depending on a condition?
Show answer
impl Summary in a return position represents one hidden concrete type, so every return path must produce the same type.