Sub topic 10
Fixing unsatisfied trait bounds
This chapter assumes you can read a rustc diagnostic (error code, primary span, labels, notes, help) and know basic Rust: functions, structs, enums, and references. It builds on the mismatched types chapter, because many trait errors look like type errors at first.
What a trait bound is
A trait is a set of behavior a type can provide. A trait bound is a requirement that a type must implement a given trait. Operators, println!, and generic functions all rely on bounds. When a type does not meet one, rustc reports E0277.
fn main() {
let total: i32 = 5;
let extra: f64 = 1.5;
println!("{}", total + extra);
}rustc reports E0277: cannot add f64 to i32. The + operator is defined by the Add trait, and i32 only implements Add<i32>, not Add<f64>. The note lists the Add implementations that do exist. This is a good habit to copy: read the note to see what the compiler would accept.
Fix it by making both operands the same type:
fn main() {
let total: i32 = 5;
let extra: f64 = 1.5;
println!("{}", total as f64 + extra);
}Reading the diagnostic
An E0277 message usually has three parts.
- The message names the type and the missing trait: "the trait bound
X: Traitis not satisfied". - A label on the call or operator shows where the requirement came from.
- A "required by a bound in" note points to the function or type that demanded the trait.
The last note matters most. The error is often reported at your call site, but the requirement lives in the signature of the function you called.
Missing implementations on your own types
A common case is printing a struct with {} or {:?}.
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}rustc reports that Point does not implement Debug, and the help suggests adding #[derive(Debug)]. A derive attribute asks the compiler to generate the trait implementation for you.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?} {} {}", p, p.x, p.y);
}Note that {} needs Display, which has no derive. For Display you write the impl yourself.
Missing bounds in generic functions
The second common case is a generic function that uses an operation without declaring it.
fn largest<T>(items: &[T]) -> &T {
let mut best = &items[0];
for item in items {
if item > best {
best = item;
}
}
best
}Comparing with > needs PartialOrd. Inside a generic function, T could be any type, so the compiler requires you to say what T can do. Add the bound:
fn largest<T: PartialOrd>(items: &[T]) -> &T {
let mut best = &items[0];
for item in items {
if item > best {
best = item;
}
}
best
}
fn main() {
println!("{}", largest(&[3, 9, 4]));
}Choosing a fix
| Situation | Fix |
|---|---|
| Your type lacks a derivable trait (`Debug`, `Clone`, `PartialEq`) | Add `#[derive(...)]` |
| Your type lacks `Display` or a custom trait | Write an `impl` block |
| Generic `T` lacks a capability | Add a bound such as `T: PartialOrd` |
| Mixed numeric types | Convert with `as` or `From` |
Exercise
A generic function fn show<T>(x: T) { println!("{}", x); } fails with E0277. What is missing, and how do you fix it?
Show answer
The {} format needs T to implement Display, and the signature does not promise that. Change the signature to fn show<T: std::fmt::Display>(x: T).
Exercise
You get E0277 saying Point does not implement Clone when you call p.clone(). What is the smallest fix?
Show answer
Add Clone to the derive attribute on the struct, for example #[derive(Debug, Clone)]. This works if every field also implements Clone.