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 fonction générique sans borne :
Tpeut être n'importe quel type. Le corps utilise>, mais rien ne promet queTsait se comparer. E0369, binary operation `>` cannot be applied to type `&T`.A generic function with no bound:Tcan be any type. The body uses>, but nothing promises thatTcan be compared. E0369, binary operation `>` cannot be applied to type `&T`. - La borne
T: PartialOrdécrit le contrat dans la signature : seuls les types qui implémententPartialOrdentrent. En échange, le corps a le droit d'utiliser>.i32,&stretf64ont signé.The boundT: PartialOrdwrites the contract into the signature: only types that implementPartialOrdget in. In return, the body may use>.i32,&strandf64have signed. - 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. - Signer le contrat :
#[derive(PartialOrd)](avecPartialEq, qu'il exige) écrit l'impl. Pas de classe de base, pas de parenté :Colisdéclare une capacité, et la fonction l'accepte.Signing the contract:#[derive(PartialOrd)](withPartialEq, which it requires) writes theimpl. No base class, no parentage:Colisdeclares a capability, and the function accepts it.
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.5T: 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à.
Displayformatait nos messages,Errorstructurait nos erreurs,Fromfaisait marcher le?(E0277, E0119),PartialEqpermettait==. 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>etConnexion<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
- Volume 5, numéro 01 de The Rust Loop, Traits & generics, ou le polymorphisme à coût zéro, avec un compteur de copies interactif et trois refus de terrain (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants. - The Rust Book : Generic Data Types et Traits
- Index des erreurs : E0369
- Le schéma de nommage des symboles v0
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.5T: 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.
Displayformatted our messages,Errorstructured our errors,Frommade?work (E0277, E0119),PartialEqallowed==. They aren’t separate mechanisms, just ordinary standard library traits. - Type-state costs nothing because of it.
Connexion<Ouverte>andConnexion<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
- Volume 5, issue 01 of The Rust Loop, Traits & generics, or zero-cost polymorphism, with an interactive copy counter and three field refusals (link at the bottom of the page).
- Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants. - The Rust Book: Generic Data Types and Traits
- Error index: E0369
- The v0 symbol mangling scheme