Sub topic 1
Standard traits as shared contracts
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Rust: structs, enums, functions, and
match. - Follow ownership and borrowing, including
&selfand&mut. - Write
impl Trait for Typeand read a generic bound such asT: Clone. - Use
println!with{}placeholders. - Handle
ResultandOptionvalues.
This chapter is the map for the rest of the tutorial. It explains what a standard trait is and which four traits we will study. It also covers the rules that decide who may implement what. Later chapters take each trait in detail.
What a trait contract is
A trait is a named set of methods that a type promises to provide. When you write impl Trait for Type, you make that promise, and the compiler checks that you kept it. Code elsewhere can then rely on the promise without knowing anything else about your type.
The standard library defines many traits so that unrelated crates agree on common operations. Printing, converting, and creating a starting value all need a shared vocabulary. Without one, every library would invent its own to_text() or make_empty(), and nothing would work together.
This tutorial covers four of these traits:
| Trait | Required method | What it promises | Can you derive it? |
|---|---|---|---|
| `Debug` | `fmt` | A developer-facing text form, used by `{:?}` | Yes |
| `Display` | `fmt` | A user-facing text form, used by `{}` | No |
| `From<T>` | `from` | Build `Self` from a `T` that cannot fail | No |
| `Default` | `default` | Build a standard initial value | Yes |
Debug and Display both have a method named fmt, but they are different traits with different jobs. Into is a companion of From. You do not usually implement Into yourself.
A contract lets code stay generic
The value of a contract shows up in generic code. A generic function declares what it needs with a trait bound, and the compiler rejects any type that does not meet it.
use std::fmt::Debug;
fn show_all<T: Debug>(items: &[T]) {
for item in items {
println!("{:?}", item);
}
}
fn main() {
show_all(&[1, 2, 3]);
show_all(&["a", "b"]);
show_all(&[Some(1.5), None]);
}show_all knows nothing about integers, strings, or options. It knows only that T implements Debug. All three calls compile because those types keep the promise.
If you pass a type without a Debug implementation, compilation fails. The error says that T doesn't implement Debug and points at the bound. The failure happens at compile time, so there is no runtime surprise.
The same idea works for Default. This function builds a value of any type that has a standard initial value:
fn make<T: Default>() -> T {
T::default()
}
fn main() {
let n: i32 = make();
let s: String = make();
let v: Vec<u8> = make();
println!("{:?} {:?} {:?}", n, s, v);
}This prints 0 "" []. Each type decides for itself what its default looks like, and make does not care.
Conversions work the same way. A function that accepts impl Into<String> takes both &str and String:
fn greet(name: impl Into<String>) -> String {
let name: String = name.into();
format!("Hello, {}", name)
}
fn main() {
println!("{}", greet("ada"));
println!("{}", greet(String::from("grace")));
}The caller does not need to convert first. That convenience exists because String implements From<&str> and From<String>.
Where implementations come from
A type can get a trait implementation in three ways:
- The standard library already provides it. Integers,
String,Vec<T>, andOption<T>implement most of these traits. - You write it with
impl Trait for YourType. - You ask the compiler to write it with
#[derive(...)]. The next chapter covers this in detail.
Derive is only available for some traits. Of our four, only Debug and Default are derivable. Display is not, because the standard library cannot guess what text your users should see. From is not, because it cannot guess which source type you want to convert from.
Many implementations also depend on other types. A derived Debug on a struct works only if every field's type implements Debug. This rule recurs throughout the tutorial: one missing implementation inside a field stops the derive.
The orphan rule
Rust limits who may write an implementation. You may implement a trait for a type only if your crate defines the trait, the type, or both. This is the orphan rule. It guarantees that two crates can never provide conflicting implementations of the same trait for the same type.
This code does not compile because neither Display nor Vec belongs to your crate:
use std::fmt;
impl fmt::Display for Vec<i32> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "numbers")
}
}The usual workaround is a newtype, a tuple struct that wraps the foreign type. Your crate owns the wrapper, so you may implement any trait on it.
use std::fmt;
struct Numbers(Vec<i32>);
impl fmt::Display for Numbers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[")?;
for (i, n) in self.0.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", n)?;
}
write!(f, "]")
}
}
fn main() {
let n = Numbers(vec![1, 2, 3]);
println!("{}", n);
}This prints [1, 2, 3]. The ? after each write! passes a formatting error up to the caller. A later chapter on Display explains why.
Implementing the traits is a design choice
The compiler enforces the signature of each trait method. It cannot enforce the meaning, so each trait carries conventions you should follow:
Debugoutput is for programmers. Make it complete and unambiguous. It need not look pretty.Displayoutput is for end users. Make it short and readable. Do not put internal details in it.Fromconversions should be lossless and should never fail or panic. If a conversion can fail, a different trait,TryFrom, is the right one.Defaultshould return a sensible, valid starting value, not a placeholder that breaks later.
A type that breaks these conventions still compiles, but it surprises every caller who relied on the shared meaning. That surprise is the real cost of a broken contract.
The conventions also explain a few details of the standard library:
DebugandDisplayare separate traits because developers and users want different text.Fromhas no failing form because the signature returnsSelf, not aResult.- Implementing
Fromautomatically gives youInto, so you write the conversion once and callers can use either direction.
Common mistakes at this stage
- Forgetting that derive needs every field to qualify. A struct with one field whose type lacks
Debugcannot deriveDebug. Either add the derive on the inner type or implement the trait by hand. - Expecting
{}to work on any type. Only types that implementDisplaycan be printed with{}. Use{:?}while debugging if the type derivesDebug. - Fighting the orphan rule. If the compiler reports that the impl violates it, do not look for a way around it. Wrap the type in a newtype instead.
- Treating
Defaultas "zero everywhere". A zero or empty value is not always valid for your type. Check before you derive.
What comes next
The following chapters take each trait in turn. They start with derive, then cover Debug and its two output formats, then Display and the to_string() method it provides. After that they cover From, Into, TryFrom, and the ? operator, and finish with Default and struct update syntax. The last chapter helps you choose among derive and manual implementations.
Exercise
You write struct Meters(f64); and want println!("{}", Meters(3.5)) to work. You also want the same for Vec<i32>, so you write impl fmt::Display for Vec<i32> in your crate. Which of the two attempts compiles, and why? What would you change for the other?
Show answer
The Meters attempt compiles once you write impl fmt::Display for Meters, because your crate defines the type, and that satisfies the orphan rule. The impl fmt::Display for Vec<i32> attempt does not compile, because both Display and Vec are defined outside your crate. To fix it, wrap the vector in a newtype such as struct Numbers(Vec<i32>); and implement Display for the wrapper.
Exercise
A generic function is declared as fn describe<T: Debug + Default>() -> String. Name two kinds of types that fail to satisfy this bound, and say where the compiler reports the problem.
Show answer
Any type that lacks Debug fails, such as a struct with no derive and no manual implementation. Any type that lacks Default fails, such as a struct with no default value defined. The compiler reports the problem at compile time, at the call site that uses the unsupported type, with a message that the type does not implement the required trait.