Describe the capability.
Share behavior through a named contract.
01 Understand the contract
A trait describes behavior that types can implement. A trait method can have a default body, and an impl provides the type-specific behavior. Bounds such as T: Summary let a function rely on that capability without knowing the concrete type. Traits are also used for standard operations such as Debug, Clone, Iterator, and From. Keep the contract cohesive: a type that can summarize itself need not also know how to persist itself or serve an HTTP request.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
trait Summary {
fn summary(&self) -> String;
}
struct Build {
passed: u32,
}
impl Summary for Build {
fn summary(&self) -> String {
format!("{} checks passed", self.passed)
}
}
fn report(item: &impl Summary) {
println!("{}", item.summary());
}
fn main() {
report(&Build { passed: 12 });
}12 checks passed
- 1
Summary declares one capability.
- 2
Build implements that behavior using its field.
- 3
The report function accepts any type implementing Summary.
cargo run -p lesson_traits03 Mind the boundary
04 Your next build
Implement a Named trait for a Project and test the returned borrowed name.
Reveal one possible solution +
trait Named {
fn name(&self) -> &str;
}
struct Project(String);
impl Named for Project {
fn name(&self) -> &str {
&self.0
}
}
fn main() {
let p = Project("Lab".into());
assert_eq!(p.name(), "Lab");
}05 Check your reasoning
What does a trait bound declare?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.