« binary operation > cannot be applied to type &T » : traits et generics en Rust, le modèle mental (E0369) "binary operation > cannot be applied to type &T": traits and generics in Rust, the mental model (E0369)

Un trait est un contrat, la borne T: PartialOrd la clause qu'une fonction générique exige à l'entrée. Sans borne, E0369 ; un type qui n'a pas signé, E0277. Puis la monomorphisation : une écriture, une copie par type, quatre symboles dans le binaire. Animation et sorties réelles de rustc.A trait is a contract, the bound T: PartialOrd the clause a generic function requires at the door. No bound, E0369; a type that hasn't signed, E0277. Then monomorphization: one writing, one copy per type, four symbols in the binary. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
TraitsTraits
PubliéPublished

En bref. Rust n’a pas d’héritage. Pour partager un comportement entre types, il a les traits : des contrats qu’un type décide d’honorer. Une fonction générique dit quel contrat elle exige avec une borne, T: PartialOrd. Oubliez la borne, et le corps ne peut rien faire de T : E0369, binary operation > cannot be applied to type &T. Passez un type qui n’a pas signé, et l’appel est refusé : E0277. À la compilation, chaque type utilisé reçoit sa propre copie de la fonction : la monomorphisation, qui rend les generics gratuits à l’exécution.

Le modèle en une phrase

Un trait est un contrat ; une borne est la clause qu’une fonction générique exige à l’entrée ; la monomorphisation imprime une copie de la fonction pour chaque type qui a signé.

La borne protège dans les deux sens. Le corps n’utilise que ce que le contrat garantit, et l’appelant ne peut faire entrer que des types qui l’ont signé. Ce qu’on vérifie ici, c’est une capacité, pas une parenté.

In short. Rust has no inheritance. To share behaviour between types, it has traits: contracts a type decides to honour. A generic function states which contract it requires with a bound, T: PartialOrd. Forget the bound, and the body can’t do anything with T: E0369, binary operation > cannot be applied to type &T. Pass a type that hasn’t signed, and the call is refused: E0277. At compile time, each type used gets its own copy of the function: monomorphization, which makes generics free at runtime.

The model in one sentence

A trait is a contract; a bound is the clause a generic function requires at the door; monomorphization prints one copy of the function for each type that has signed.

The bound protects both ways. The body only uses what the contract guarantees, and the caller can only bring in types that have signed it. What’s checked is a capability, not a parentage.

fn plus_grand<T>(liste: &[T]) -> &T {
let mut max = &liste[0];
for x in liste {
if x > max { max = x; }
}
max
}
Une borne, des copiesOne bound, many copiesla borne dit ce que T sait fairethe bound says what T can doles typesthe typesplus_grand<T>T : aucune borneT: no boundle corps utilisethe body usesif x > max> sur T ? rien ne le promet> on T? nothing promises iti32&strf64Colisle contratthe contracttrait PartialOrdimplémenté par :implemented by:i32&strf64…E0369 · binary operation `>` cannot be applied to type `&T`E0369 · binary operation `>` cannot be applied to type `&T`vérifié avec rustc 1.100checked with rustc 1.100
  1. Une fonction générique sans borne : T peut être n'importe quel type. Le corps utilise >, mais rien ne promet que T sait se comparer. E0369, binary operation `>` cannot be applied to type `&T`.A generic function with no bound: T can be any type. The body uses >, but nothing promises that T can be compared. E0369, binary operation `>` cannot be applied to type `&T`.
  2. La borne T: PartialOrd écrit le contrat dans la signature : seuls les types qui implémentent PartialOrd entrent. En échange, le corps a le droit d'utiliser >. i32, &str et f64 ont signé.The bound T: PartialOrd writes the contract into the signature: only types that implement PartialOrd get in. In return, the body may use >. i32, &str and f64 have signed.
  3. Un type à nous, Colis, n'a pas signé le contrat. L'appel est refusé à l'entrée, pas au milieu du corps : E0277, can't compare `Colis` with `Colis`, et rustc pointe la borne qui l'exige.One of our types, Colis, hasn't signed the contract. The call is rejected at the door, not in the middle of the body: E0277, can't compare `Colis` with `Colis`, and rustc points at the bound that requires it.
  4. Signer le contrat : #[derive(PartialOrd)] (avec PartialEq, qu'il exige) écrit l'impl. Pas de classe de base, pas de parenté : Colis déclare une capacité, et la fonction l'accepte.Signing the contract: #[derive(PartialOrd)] (with PartialEq, which it requires) writes the impl. No base class, no parentage: Colis declares a capability, and the function accepts it.
Traits et generics en Rust : la borne T: PartialOrd est un contrat écrit dans la signature. Sans elle, le corps ne peut pas comparer (E0369) ; un type qui ne l'implémente pas est refusé à l'appel (E0277).Traits and generics in Rust: the bound T: PartialOrd is a contract written in the signature. Without it, the body can't compare (E0369); a type that doesn't implement it is rejected at the call (E0277).

Sans borne : E0369

Une fonction qui renvoie le plus grand élément, écrite une fois pour tous les types :

fn plus_grand<T>(liste: &[T]) -> &T {
    let mut max = &liste[0];
    for x in liste {
        if x > max {
            max = x;
        }
    }
    max
}
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> borne.rs:4:14
  |
4 |         if x > max {
  |            - ^ --- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn plus_grand<T: std::cmp::PartialOrd>(liste: &[T]) -> &T {
  |                ++++++++++++++++++++++

<T> seul veut dire « n’importe quel type ». Le compilateur prend ce « n’importe » au sérieux : un type qui ne sait pas se comparer reste possible, donc > n’est pas permis. Ce n’est pas un défaut d’inférence. rustc vérifie le corps une seule fois, pour tous les T possibles, et non à chaque appel comme le font les templates C++.

La borne : le contrat dans la signature

fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T {
    // … même corps
}

fn main() {
    println!("{}", plus_grand(&[3, 9, 4]));
    println!("{}", plus_grand(&["kiwi", "abricot", "poire"]));
    println!("{}", plus_grand(&[2.5, 1.0]));
}
9
poire
2.5

T: PartialOrd est une clause : « je n’accepte que les types qui savent se comparer ». En échange, le corps a le droit d’utiliser >. La signature dit maintenant tout ce dont la fonction a besoin, sans qu’on ait à lire le corps.

Quand les bornes s’allongent, where les sort de la ligne : fn f<T>(x: T) where T: PartialOrd + Display. Pour un argument qu’on n’a pas besoin de nommer, impl Trait est un raccourci : fn afficher(x: impl Display) est la même fonction générique que fn afficher<T: Display>(x: T).

Un type qui n’a pas signé : E0277

struct Colis { poids: u32 }

let c = [Colis { poids: 3 }, Colis { poids: 9 }];
let m = plus_grand(&c);
error[E0277]: can't compare `Colis` with `Colis`
  --> impl_manque.rs:14:24
   |
14 |     let m = plus_grand(&c);
   |             ---------- ^^ no implementation for `Colis < Colis` and `Colis > Colis`
   |             |
   |             required by a bound introduced by this call
   |
   = help: the trait `PartialOrd` is not implemented for `Colis`
note: required by a bound in `plus_grand`
  --> impl_manque.rs:3:18
   |
 3 | fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T {
   |                  ^^^^^^^^^^ required by this bound in `plus_grand`
help: consider annotating `Colis` with `#[derive(PartialOrd)]`

Le refus arrive à l’appel, à la porte, avec la clause qui l’exige. Il n’arrive jamais au milieu du corps. Pour signer, on écrit l’impl, ou on la dérive :

#[derive(PartialEq, PartialOrd)]
struct Colis { poids: u32 }

PartialEq n’est pas optionnel. Avec #[derive(PartialOrd)] seul, rustc répond can’t compare Colis with Colis et précise : the trait PartialEq is not implemented for Colis, required by a bound in PartialOrd. PartialEq est un supertrait de PartialOrd : le contrat de la comparaison inclut celui de l’égalité. C’est ce qui remplace l’héritage. On ne compose pas des familles de classes, on compose des capacités.

La monomorphisation : une écriture, N copies

Appelons plus_grand avec quatre types, puis listons ses symboles avec nm :

$ rustc --edition 2024 ok.rs && nm ok | grep plus_grand
0000000100000888 t __RINvCs2zTshuCd3Et_2ok10plus_grandNtB2_5ColisEB2_
0000000100000940 t __RINvCs2zTshuCd3Et_2ok10plus_grandReEB2_
00000001000009f8 t __RINvCs2zTshuCd3Et_2ok10plus_granddEB2_
0000000100000ab0 t __RINvCs2zTshuCd3Et_2ok10plus_grandlEB2_

Quatre fonctions dans le binaire pour une seule écrite. Le suffixe de chaque symbole encode le type, selon le schéma de nommage v0 de Rust : NtB2_5Colis pour Colis, Re pour &str, d pour f64, l pour i32. (On compile sans -O : le build optimisé retire ces symboles locaux du binaire, et l’optimiseur peut aussi fondre une copie dans son appelant. Les copies existent quand même ; elles sont simplement moins visibles.)

        à la compilation
fn plus_grand<T: PartialOrd>  ──┬──▶ plus_grand::<i32>
                                ├──▶ plus_grand::<&str>
                                ├──▶ plus_grand::<f64>
                                └──▶ plus_grand::<Colis>

Chaque copie est du code ordinaire, comme si on avait écrit plus_grand_i32 à la main : l’appel est direct, l’optimiseur peut tout inliner, il n’y a rien à chercher à l’exécution. C’est le sens de « coût zéro ». La facture arrive ailleurs : une copie par type, donc un binaire plus gros et une compilation plus longue quand une grosse fonction est instanciée pour beaucoup de types.

La limite : une copie, un type

fn etiquette(lourd: bool) -> impl Display {
    if lourd { 42 } else { "léger" }
}
error[E0308]: `if` and `else` have incompatible types
 --> impltrait.rs:3:28
  |
3 |     if lourd { 42 } else { "léger" }
  |                --          ^^^^^^^ expected integer, found `&str`
  |                |
  |                expected because of this
  |
help: you could change the return type to be a boxed trait object
  |
2 - fn etiquette(lourd: bool) -> impl Display {
2 + fn etiquette(lourd: bool) -> Box<dyn Display> {

En retour, impl Display promet un type concret, choisi par la fonction et caché à l’appelant. La monomorphisation exige de connaître ce type à la compilation, et il ne peut pas dépendre d’une valeur connue seulement à l’exécution. rustc propose l’autre branche : Box<dyn Display>, un seul code qui découvre le type à l’exécution. C’est le prochain article.

Ce que l’image cache

  • Les traits, vous les connaissez déjà. Display formatait nos messages, Error structurait nos erreurs, From faisait marcher le ? (E0277, E0119), PartialEq permettait ==. Ce ne sont pas des mécanismes à part, mais des traits ordinaires de la bibliothèque standard.
  • Le type-state ne coûte rien grâce à elle. Connexion<Ouverte> et Connexion<Fermee> (newtype et type-state) deviennent deux copies sans trace du paramètre à l’exécution.
  • Concret par défaut. Trois paramètres de type pour une fonction appelée avec un seul type, c’est de l’abstraction qui ne réutilise rien et rend la signature illisible. Le générique se justifie quand il sert vraiment plusieurs types.
  • Les bornes se vérifient avant les appels. Contrairement aux templates C++, le corps d’une fonction générique Rust est vérifié une fois contre ses bornes. Une erreur dans le corps apparaît même si personne ne l’appelle.

Pour aller plus loin

No bound: E0369

A function that returns the largest element, written once for every type:

fn plus_grand<T>(liste: &[T]) -> &T {
    let mut max = &liste[0];
    for x in liste {
        if x > max {
            max = x;
        }
    }
    max
}
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> borne.rs:4:14
  |
4 |         if x > max {
  |            - ^ --- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn plus_grand<T: std::cmp::PartialOrd>(liste: &[T]) -> &T {
  |                ++++++++++++++++++++++

<T> alone means “any type”. The compiler takes that “any” seriously: a type that can’t be compared is still possible, so > isn’t allowed. It isn’t an inference failure. rustc checks the body once, for every possible T, not at each call the way C++ templates do.

The bound: the contract in the signature

fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T {
    // … same body
}

fn main() {
    println!("{}", plus_grand(&[3, 9, 4]));
    println!("{}", plus_grand(&["kiwi", "abricot", "poire"]));
    println!("{}", plus_grand(&[2.5, 1.0]));
}
9
poire
2.5

T: PartialOrd is a clause: “I only accept types that can be compared”. In return, the body may use >. The signature now says everything the function needs, without reading the body.

When bounds grow long, where moves them off the line: fn f<T>(x: T) where T: PartialOrd + Display. For an argument you don’t need to name, impl Trait is a shorthand: fn afficher(x: impl Display) is the same generic function as fn afficher<T: Display>(x: T).

A type that hasn’t signed: E0277

struct Colis { poids: u32 }

let c = [Colis { poids: 3 }, Colis { poids: 9 }];
let m = plus_grand(&c);
error[E0277]: can't compare `Colis` with `Colis`
  --> impl_manque.rs:14:24
   |
14 |     let m = plus_grand(&c);
   |             ---------- ^^ no implementation for `Colis < Colis` and `Colis > Colis`
   |             |
   |             required by a bound introduced by this call
   |
   = help: the trait `PartialOrd` is not implemented for `Colis`
note: required by a bound in `plus_grand`
  --> impl_manque.rs:3:18
   |
 3 | fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T {
   |                  ^^^^^^^^^^ required by this bound in `plus_grand`
help: consider annotating `Colis` with `#[derive(PartialOrd)]`

The refusal comes at the call, at the door, with the clause that requires it. It never comes in the middle of the body. To sign, you write the impl, or derive it:

#[derive(PartialEq, PartialOrd)]
struct Colis { poids: u32 }

PartialEq isn’t optional. With #[derive(PartialOrd)] alone, rustc answers can’t compare Colis with Colis and adds: the trait PartialEq is not implemented for Colis, required by a bound in PartialOrd. PartialEq is a supertrait of PartialOrd: the comparison contract includes the equality one. That’s what replaces inheritance. You don’t compose families of classes, you compose capabilities.

Monomorphization: one writing, N copies

Let’s call plus_grand with four types, then list its symbols with nm:

$ rustc --edition 2024 ok.rs && nm ok | grep plus_grand
0000000100000888 t __RINvCs2zTshuCd3Et_2ok10plus_grandNtB2_5ColisEB2_
0000000100000940 t __RINvCs2zTshuCd3Et_2ok10plus_grandReEB2_
00000001000009f8 t __RINvCs2zTshuCd3Et_2ok10plus_granddEB2_
0000000100000ab0 t __RINvCs2zTshuCd3Et_2ok10plus_grandlEB2_

Four functions in the binary for one written. Each symbol’s suffix encodes the type, following Rust’s v0 mangling scheme: NtB2_5Colis for Colis, Re for &str, d for f64, l for i32. (We build without -O: the optimised build strips these local symbols from the binary, and the optimiser may also fold a copy into its caller. The copies still exist; they are just harder to see.)

        at compile time
fn plus_grand<T: PartialOrd>  ──┬──▶ plus_grand::<i32>
                                ├──▶ plus_grand::<&str>
                                ├──▶ plus_grand::<f64>
                                └──▶ plus_grand::<Colis>

Each copy is ordinary code, as if you’d written plus_grand_i32 by hand: the call is direct, the optimiser can inline everything, there’s nothing to look up at runtime. That’s what “zero cost” means. The bill arrives elsewhere: one copy per type, so a bigger binary and a longer build when a large function is instantiated for many types.

The limit: one copy, one type

fn etiquette(lourd: bool) -> impl Display {
    if lourd { 42 } else { "léger" }
}
error[E0308]: `if` and `else` have incompatible types
 --> impltrait.rs:3:28
  |
3 |     if lourd { 42 } else { "léger" }
  |                --          ^^^^^^^ expected integer, found `&str`
  |                |
  |                expected because of this
  |
help: you could change the return type to be a boxed trait object
  |
2 - fn etiquette(lourd: bool) -> impl Display {
2 + fn etiquette(lourd: bool) -> Box<dyn Display> {

In return position, impl Display promises one concrete type, chosen by the function and hidden from the caller. Monomorphization needs that type at compile time, and it can’t depend on a value only known at runtime. rustc suggests the other branch: Box<dyn Display>, a single piece of code that discovers the type at runtime. That’s the next article.

What the picture hides

  • You already know traits. Display formatted our messages, Error structured our errors, From made ? work (E0277, E0119), PartialEq allowed ==. They aren’t separate mechanisms, just ordinary standard library traits.
  • Type-state costs nothing because of it. Connexion<Ouverte> and Connexion<Fermee> (newtype and type-state) become two copies with no trace of the parameter at runtime.
  • Concrete by default. Three type parameters for a function called with a single type is abstraction that reuses nothing and makes the signature unreadable. A generic earns its place when it really serves several types.
  • Bounds are checked before any call. Unlike C++ templates, the body of a generic Rust function is checked once against its bounds. An error in the body shows up even if nobody calls it.

Going further

Questions fréquentesFrequently asked questions

Que signifie « binary operation `>` cannot be applied to type `&T` » (E0369) ?What does "binary operation `>` cannot be applied to type `&T`" (E0369) mean?

Dans une fonction générique, T peut être n'importe quel type, et le compilateur ne suppose rien à son sujet. Utiliser > exige que T implémente PartialOrd ; sans le dire, rustc refuse. Le correctif est de l'écrire dans la signature : fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T. rustc le propose dans son help.In a generic function, T can be any type, and the compiler assumes nothing about it. Using > requires T to implement PartialOrd; without saying so, rustc refuses. The fix is to write it in the signature: fn plus_grand<T: PartialOrd>(liste: &[T]) -> &T. rustc suggests it in its help.

Que signifie « can't compare `Colis` with `Colis` » (E0277) ?What does "can't compare `Colis` with `Colis`" (E0277) mean?

La fonction exige T: PartialOrd, et le type passé ne l'implémente pas. rustc refuse l'appel et pointe la borne qui l'exige (required by this bound). Pour une struct à vous, #[derive(PartialEq, PartialOrd)] écrit l'implémentation ; PartialEq est obligatoire, car c'est un supertrait de PartialOrd.The function requires T: PartialOrd, and the type passed doesn't implement it. rustc rejects the call and points at the bound that requires it (required by this bound). For your own struct, #[derive(PartialEq, PartialOrd)] writes the implementation; PartialEq is mandatory, since it's a supertrait of PartialOrd.

Qu'est-ce que la monomorphisation en Rust ?What is monomorphization in Rust?

À la compilation, chaque appel d'une fonction générique avec un type concret produit une copie spécialisée de la fonction, où T est remplacé par ce type. Vérifié avec nm : une plus_grand générique appelée avec i32, &str, f64 et Colis donne quatre symboles distincts dans le binaire. L'appel est direct, sans coût à l'exécution.At compile time, each call of a generic function with a concrete type produces a specialised copy of the function, where T is replaced by that type. Verified with nm: a generic plus_grand called with i32, &str, f64 and Colis gives four distinct symbols in the binary. The call is direct, with no runtime cost.

Quel est le coût des generics en Rust ?What do generics cost in Rust?

Rien à l'exécution : chaque copie est du code ordinaire, que l'optimiseur peut inliner. Le coût est à la compilation : une copie par type utilisé, donc un binaire plus gros et une compilation plus longue quand une grosse fonction générique est instanciée pour beaucoup de types. Quand ce coût gêne, dyn Trait échange les copies contre une indirection.Nothing at runtime: each copy is ordinary code the optimiser can inline. The cost is at compile time: one copy per type used, so a bigger binary and a longer build when a large generic function is instantiated for many types. When that cost hurts, dyn Trait trades the copies for an indirection.

Pourquoi impl Trait en retour refuse-t-il deux types différents ?Why does impl Trait in return position reject two different types?

-> impl Display promet un seul type concret, choisi par la fonction et caché à l'appelant. Rendre 42 dans un cas et "léger" dans l'autre en ferait deux : rustc refuse avec E0308 (`if` and `else` have incompatible types) et propose Box<dyn Display>, un objet trait résolu à l'exécution.-> impl Display promises a single concrete type, chosen by the function and hidden from the caller. Returning 42 in one case and "léger" in the other would make two: rustc refuses with E0308 (`if` and `else` have incompatible types) and suggests Box<dyn Display>, a trait object resolved at runtime.

RustTraitsGenericsMonomorphisationE0369Modèle mental

← Tous les articlesAll articles