Pular para o conteúdo
TE821 · Tipos · error

Operador exige trait bound no parâmetro de tipo

Um operador é usado sobre um parâmetro de tipo genérico que não carrega o trait bound correspondente. Sem ele, o compilador não garante que a operação vale para todo argumento de tipo possível.

Why this fires

An operator is used on a generic type parameter that doesn't carry the corresponding trait bound. Without the bound the compiler can't guarantee the operation is valid for every possible type argument.

fn add_two<T>(a: T, b: T) -> T {
    return a + b
    //     ^^^^^ error[TE821]: operator `+` requires bound `Add` on `T`
}

Fix it

Add the missing bound in either the angle-bracket or where form:

// Angle-bracket form
fn add_two<T: Add>(a: T, b: T) -> T {
    return a + b
}

// where form (useful when multiple bounds are needed)
fn add_two<T>(a: T, b: T) -> T where T: Add {
    return a + b
}

Operator → bound mapping

Operator Required bound
+ Add
- (binary) Sub
* Mul
/ Div
% Mod
==, != Eq
<, >, <=, >= Ord

Only binary operators are gated. Unary - on a generic parameter is not checked yet (its Neg bound is recognised but unenforced).

See also

  • TE820 — the concrete type passed to a bounded generic doesn't implement the required trait.
  • TE822 — bound names an unknown trait.

Veja também

Buscar no Zolo

9 resultados

en