Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 25 / 53

Describe the capability.

Share behavior through a named contract.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/traits/src/main.rs
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 });
}
↳ EXPECTED OUTPUT
12 checks passed
  1. 1

    Summary declares one capability.

  2. 2

    Build implements that behavior using its field.

  3. 3

    The report function accepts any type implementing Summary.

From the extracted rust-workbench folder
cargo run -p lesson_traits

03 Mind the boundary

04 Your next build

A SMALL MISSION

Implement a Named trait for a Project and test the returned borrowed name.

Reveal one possible solution +
solutions/traits/src/main.rs
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

QUICK SIGNAL CHECK

What does a trait bound declare?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.