Sub topic 1
Standard traits as shared contracts
Prerequisites
This chapter assumes you can:
- Read basic Rust: structs, enums, functions, and
match. - Explain ownership and borrowing at a working level.
- Write
impl Trait for Typeand understand what a trait is. - Use
println!with format strings. - Handle
ResultandOptionvalues.
What a standard trait is
A trait is a contract. It lists methods a type promises to provide. The standard library defines many traits so that unrelated code can agree on common behavior without knowing about each other's types.
This tutorial covers four of them:
| Trait | Contract | Typical use |
|---|---|---|
| `Debug` | Write a value as text for developers | `{:?}` and `{:#?}` in logs and tests |
| `Display` | Write a value as text for end users | `{}` and `to_string()` |
| `From` | Build this type from another type | Conversions, `.into()`, and `?` |
| `Default` | Produce a standard initial value | `Default::default()` |
Each one answers a different question. How do I inspect this value? How do I show it to a person? How do I get it from something else? What is its starting value?
Why the contract matters
Library code can demand a trait and then work with any type that meets it. The standard macros and functions do this constantly. println!("{:?}", x) works for any x that implements Debug.
You can write the same kind of requirement yourself with a trait bound.
use std::fmt::Debug;
fn show<T: Debug>(value: T) {
println!("{:?}", value);
}
#[derive(Debug)]
struct Marker;
fn main() {
show(42);
show("hello");
show(Marker);
}show does not know what T is. It only knows that T promises Debug. If you remove #[derive(Debug)] from Marker, the call show(Marker) fails to compile. The compiler reports that Marker doesn't implement Debug. That error is the contract being enforced.
Two ways to implement a trait
You can satisfy a contract in two ways:
- Derive it. Write
#[derive(Debug)]above the type and the compiler generates a standard implementation. This is the right choice when the standard behavior is what you want. - Implement it by hand. Write
impl Trait for Typeyourself when the standard behavior is wrong or doesn't exist.
Not every trait can be derived. Debug and Default can. Display and From cannot, because there is no single correct output or source type for the compiler to guess. You always write those yourself.
Common errors
- Missing trait on a field. Deriving
Debugon a struct requires every field's type to implementDebugas well. One field without it breaks the derive. - Using
{}on a type with noDisplay. The compiler reports that the type doesn't implementstd::fmt::Display. DeriveDebugand use{:?}, or implementDisplay. - Expecting
Displayto be derivable. There is no#[derive(Display)]in the standard library.
The following chapters take the traits one at a time, starting with derive and Debug.
Exercise
A struct has three fields. Two are String and one is a type Token that has no Debug implementation. What happens if you add #[derive(Debug)] to the struct, and what are two ways to fix it?
Show answer
Compilation fails because the derived implementation needs every field to implement Debug, and Token does not. You can fix it by adding #[derive(Debug)] to Token, or by implementing Debug for the struct by hand and leaving Token out of the output.