Sub topic 10
Fixing unsatisfied trait bounds
This chapter assumes you can read a basic rustc diagnostic (code, message, span, notes, help). It also assumes you know what a trait is, how to write a generic function, and how #[derive] works. If the layout of a diagnostic is unfamiliar, review the chapter on diagnostic anatomy first.
What an unsatisfied trait bound is
A trait bound is a requirement that a type implements a trait. Bounds appear in generic signatures, such as T: Display. They also appear implicitly in operators (+ needs Add), in println!("{}") (needs Display), and in the ? operator.
When you use a type where a bound is required and the type does not implement the trait, rustc reports E0277: "the trait bound X: Trait is not satisfied." The message varies with the trait. For common traits the text is friendlier, such as "cannot add f64 to i32" or "Point doesn't implement std::fmt::Display". The cause is the same each time. Some code needs a capability that a type lacks.
Method calls are a close relative. If a method exists only when its type satisfies certain bounds, rustc reports E0599 ("method exists but its trait bounds were not satisfied") instead of E0277. The fixes are the same.
The two questions to ask
Read an E0277 diagnostic by answering two questions.
- Which type is missing which trait? The message and the
help: the trait ... is not implemented for ...line state this. - Who demanded the trait? Look for lines starting
note: required by a bound in .... They point at the function, operator, or impl that imposed the requirement.
Mismatched operands: `i32 + f64`
This is the example from the spine. Rust has no implicit numeric conversion.
fn main() {
let total: i32 = 5;
let extra: f64 = 1.5;
println!("{}", total + extra);
}rustc reports error[E0277]: cannot add f64 to i32`, with the label "no implementation for i32 + f64" and the help the trait Add<f64> is not implemented for i32. The help names the exact trait: there is an Add<i32> for i32, but no Add<f64>`.
The fix is to make both operands the same type.
fn main() {
let total: i32 = 5;
let extra: f64 = 1.5;
println!("{}", total as f64 + extra);
}Use f64::from(total) instead of as when the conversion is lossless. From documents intent and refuses conversions that could lose data.
Missing `Display` on your own type
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{}", p);
}The error is "Point doesn't implement std::fmt::Display". The note adds that the type cannot be formatted with the default formatter. {} needs Display, which has no derive because Rust cannot guess a user-facing format. You have two options.
For debugging output, derive Debug and use {:?}:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}For user-facing output, implement Display yourself:
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{p}");
}Generic functions: add the bound
When the missing trait belongs to a generic parameter T, the function body uses a capability that the signature never promised.
fn print_all<T>(items: &[T]) {
for item in items {
println!("{}", item);
}
}rustc says "T doesn't implement std::fmt::Display" and offers help: consider restricting type parameter T``. This diagnostic is one where the suggestion is correct. Add the bound to the signature:
use std::fmt::Display;
fn print_all<T: Display>(items: &[T]) {
for item in items {
println!("{}", item);
}
}
fn main() {
print_all(&[1, 2, 3]);
print_all(&["a", "b"]);
}Add the smallest bound that the body needs. Do not add Clone + Debug + Display speculatively, because every bound narrows the set of callers. When there are several bounds, a where clause keeps the signature readable:
use std::fmt::{Debug, Display};
fn report<T>(value: T) -> String
where
T: Display + Debug,
{
format!("{value} / {value:?}")
}
fn main() {
println!("{}", report(42));
}The caller side: the bound is in someone else's signature
Often the error appears at a call site, not inside a generic body. The required by a bound in note then tells you which function imposed the bound.
use std::collections::HashMap;
struct Key {
id: u32,
}
fn main() {
let mut map = HashMap::new();
map.insert(Key { id: 1 }, "one");
}Here insert is only available when the key implements Eq and Hash, so rustc reports E0599 and lists the unsatisfied bounds. Because Key is your type and its fields already implement these traits, derive supplies them:
use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash)]
struct Key {
id: u32,
}
fn main() {
let mut map = HashMap::new();
map.insert(Key { id: 1 }, "one");
println!("{}", map.len());
}Eq requires PartialEq, so derive both. A derive fails with its own E0277 if a field lacks the trait. A struct holding an f64 cannot derive Eq or Hash, because floating-point NaN != NaN. Use PartialEq alone, or store an integer or ordered wrapper type.
Other common sources
| Symptom in the message | Cause | Typical fix |
|---|---|---|
| `the `?` operator can only be used in a function that returns `Result` or `Option`` | `?` used in a function returning `()` | Change the return type, for example `fn main() -> Result<(), E>` |
| `a value of type `Vec<i32>` cannot be built from an iterator over elements of type `&i32`` | `collect` target does not match the item type | Add `.copied()` or `.cloned()` before `collect` |
| `` `Rc<i32>` cannot be sent between threads safely`` | `thread::spawn` requires `Send` | Use `Arc` instead of `Rc` |
| `the size for values of type `str` cannot be known at compilation time` | An unsized type used by value | Use `&str` or `String` |
| `the trait bound `T: Clone` is not satisfied` | Generic code calls `.clone()` | Add `T: Clone` |
The ? case is runnable with a small fix:
use std::num::ParseIntError;
fn main() -> Result<(), ParseIntError> {
let n: i32 = "42".parse()?;
println!("{n}");
Ok(())
}For the collect case, the iterator v.iter() yields &i32, so convert before collecting:
fn main() {
let v = vec![1, 2, 3];
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
let copy: Vec<i32> = v.iter().copied().collect();
println!("{doubled:?} {copy:?}");
}Limits: you cannot implement every trait
Sometimes the missing implementation is for a type you do not own, such as impl Display for Vec<i32>. The orphan rule (error E0117) forbids implementing a foreign trait for a foreign type. Wrap the type in a newtype you own and implement the trait on the wrapper:
use std::fmt;
struct Numbers(Vec<i32>);
impl fmt::Display for Numbers {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let parts: Vec<String> = self.0.iter().map(|n| n.to_string()).collect();
write!(f, "[{}]", parts.join(", "))
}
}
fn main() {
println!("{}", Numbers(vec![1, 2, 3]));
}A repeatable checklist
- Run
cargo checkand read the first E0277 only. - Name the missing trait and the type from the message and help line.
- Follow the
required by a bound innote to see who asked for it. - Pick the lightest fix: convert the value, derive, add a bound, implement manually, or wrap in a newtype.
- Use
rustc --explain E0277if the cause is still unclear. - Re-run
cargo check. Later errors may disappear on their own.
Exercise
This function fails to compile with E0277 on the println! line. Rewrite its signature so it compiles and can be called with both &[1, 2] and &["a"].
fn show_first<T>(items: &[T]) {
println!("{}", items[0]);
}
Show answer
The body needs Display, and the signature does not promise it. Add the bound:
use std::fmt::Display;
fn show_first<T: Display>(items: &[T]) {
println!("{}", items[0]);
}
Both i32 and &str implement Display, so both calls compile.
Exercise
A struct Id { value: f64 } is used as a HashMap key with #[derive(PartialEq, Eq, Hash)], and the derive reports E0277. Why does it fail, and what are two ways to fix it?
Show answer
f64 implements neither Eq nor Hash, because NaN is not equal to itself. A derive requires every field to implement the trait. Fix it by changing the field to an integer type (for example, store the value in fixed-point units as i64), or by wrapping the float in an ordered type that defines total ordering and hashing. If you do not need map keys, derive only PartialEq.