Skip to content
TE820 · Type · error

Type does not implement a required trait

A generic function is called with a type argument that doesn't implement a trait required by one of its bounds.

Why this fires

A generic function is called with a type argument that doesn't implement a trait required by one of its bounds.

fn sort_min<T: Ord>(a: T, b: T) -> T {
    if a > b { b } else { a }
}

struct Color { r: int, g: int, b: int }

sort_min(Color { r: 255, g: 0, b: 0 }, Color { r: 0, g: 0, b: 255 })
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[TE820]: type `Color` does not implement trait `Ord`

Fix it

1. Implement the required trait

Add an impl <Trait> for <Type> block. For Ord, also add the comparison operators via @op:

impl Color {
    @op("<")
    fn lt(self, other: Color) -> bool { self.r < other.r }
    @op(">")
    fn gt(self, other: Color) -> bool { self.r > other.r }
}

impl Ord for Color {
    fn cmp(self, other: Color) -> int {
        if self.r < other.r { 0 - 1 } else { if self.r > other.r { 1 } else { 0 } }
    }
}

2. Use a concrete overload instead

If you only need the operation for one specific type, write a non-generic function that accepts that type directly rather than a generic with bounds.

3. Weaken the bound (if the constraint is too strict)

If the function's body only needs a subset of the trait's functionality, consider whether a less restrictive bound (or no bound at all) would suffice.

Std-trait catalogue

The following traits are recognised as built-in bounds and have primitive impls:

Trait Covers
Eq == / != on int, float, str, bool
Ord <, >, <=, >=, cmp on int, float, str
Add + on int, float, str
Sub - on int, float
Mul * on int, float
Div / on int, float
Mod % on int, float
Neg unary - on int, float
Display print-able (all primitives)
Hash hashable (all primitives)

See also

  • TE821 — operator used on an unbounded generic param.
  • TE822 — bound names an unknown trait.

See also

Search Zolo

9 results

en