« only traits defined in the current crate can be implemented » : la règle de l'orphelin en Rust, le modèle mental (E0117) "only traits defined in the current crate can be implemented": the orphan rule in Rust, the mental model (E0117)

Une impl est un couple (trait, type). Le programme entier en admet au plus une par couple, et le crate qui l'écrit doit posséder le trait ou le type. Trait et type étrangers : E0117, et la sortie par le newtype. Puis les impls génériques : chevauchement (E0119) et T nu (E0210). Animation et sorties réelles de rustc.An impl is a (trait, type) pair. The whole program allows at most one per pair, and the crate writing it must own the trait or the type. Foreign trait and type: E0117, and the way out through the newtype. Then generic impls: overlap (E0119) and bare T (E0210). Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
TraitsTraits
PubliéPublished

En bref. Depuis l’article sur les traits, on écrit des impl comme si tout était permis. Il y a une limite : on ne peut pas implémenter un trait étranger pour un type étranger. impl Display for Vec<String> donne E0117, only traits defined in the current crate can be implemented for types defined outside of the crate. Ce n’est pas une punition. C’est le prix d’une garantie : une seule impl par couple (trait, type) dans tout le programme.

Le modèle en une phrase

Une impl est un couple (trait, type) ; le programme entier en admet au plus une par couple, et seul le crate qui possède le trait ou le type a le droit de l’écrire.

Cette garantie s’appelle la cohérence. Elle permet à rustc de toujours savoir quelle impl appeler, quel que soit l’ordre des crates ou des use. La règle de l’orphelin est le moyen de la tenir sans avoir à comparer tous les crates du monde entre eux : une impl dont aucune moitié n’appartient à son crate n’a pas de parent, d’où son nom d’« orpheline ».

In short. Since the article on traits, we’ve been writing impls as if anything goes. There’s a limit: you can’t implement a foreign trait for a foreign type. impl Display for Vec<String> gives E0117, only traits defined in the current crate can be implemented for types defined outside of the crate. It isn’t a punishment. It’s the price of a guarantee: a single impl per (trait, type) pair in the whole program.

The model in one sentence

An impl is a (trait, type) pair; the whole program allows at most one per pair, and only the crate owning the trait or the type may write it.

That guarantee is called coherence. It lets rustc always know which impl to call, whatever the order of crates or uses. The orphan rule is how it’s kept without comparing every crate in the world with every other: an impl where neither half belongs to its crate has no parent, hence the name “orphan”.

struct Point { x: i32, y: i32 }
impl fmt::Display for Point { … }
println!("{}", Point { x: 1, y: 2 }); // (1, 2)
La règle de l'orphelinThe orphan ruleposséder le trait ou le typeown the trait or the typeles quatre casthe four casestype à toiyour typetype étrangerforeign typetraità toiyourstraitétrangerforeign✓Resume for Point✓Resume for Vec✓Display for Point✕Display for Vecau moins une moitié doit être à toiat least one half must be yoursqui possède les pièceswho owns the piecesstdDisplayVec<String>ton crateyour cratePointResumeListetrait étranger, type à toi : accepté · (1, 2)foreign trait, your type: accepted · (1, 2)vérifié avec rustc 1.100checked with rustc 1.100
  1. Le trait Display vient de la std, le type Point est à toi. Tu possèdes une moitié du couple : l'impl est acceptée, et elle ne peut exister nulle part ailleurs que dans ton crate.The Display trait comes from std, the Point type is yours. You own one half of the pair: the impl is accepted, and it can't exist anywhere but in your crate.
  2. L'inverse marche aussi. Resume est ton trait, Vec<String> vient de la std. Tu possèdes le trait : tu peux l'implémenter pour n'importe quel type, même étranger.The reverse works too. Resume is your trait, Vec<String> comes from std. You own the trait: you can implement it for any type, even a foreign one.
  3. Trait et type étrangers : refusé. Si c'était permis, deux crates sans lien pourraient écrire la même impl, et un programme qui dépend des deux n'aurait aucun moyen de choisir. E0117, only traits defined in the current crate can be implemented for types defined outside of the crate.Foreign trait and foreign type: refused. If it were allowed, two unrelated crates could write the same impl, and a program depending on both would have no way to choose. E0117, only traits defined in the current crate can be implemented for types defined outside of the crate.
  4. La sortie : un newtype. Liste est un type à toi qui enveloppe le Vec, donc le couple (Display, Liste) t'appartient. Il fait la même taille que le Vec : l'enveloppe ne coûte rien à l'exécution.The way out: a newtype. Liste is a type of yours wrapping the Vec, so the pair (Display, Liste) belongs to you. It's the same size as the Vec: the wrapper costs nothing at runtime.
La règle de l'orphelin en Rust : une impl est un couple (trait, type), au plus une par couple dans tout le programme, et le crate qui l'écrit doit posséder le trait ou le type. Trait et type étrangers : E0117. Sortie : le newtype.The orphan rule in Rust: an impl is a (trait, type) pair, at most one per pair in the whole program, and the crate writing it must own the trait or the type. Foreign trait and type: E0117. Way out: the newtype.

Les quatre cas

Un trait et un type, chacun à toi ou étranger : quatre combinaisons, trois acceptées.

struct Point { x: i32, y: i32 }
trait Resume { fn resume(&self) -> String; }

impl fmt::Display for Point { … }     // trait étranger, type à toi  : oui
impl Resume for Vec<String> { … }     // trait à toi, type étranger  : oui
(1, 2)
1 éléments
                 type à toi          type étranger
             ┌──────────────────┬──────────────────┐
trait à toi  │ ✓ Resume  Point  │ ✓ Resume  Vec    │
             ├──────────────────┼──────────────────┤
trait        │ ✓ Display Point  │ ✕ Display Vec    │  ← E0117
étranger     │                  │                  │
             └──────────────────┴──────────────────┘

Dans les trois cas acceptés, l’impl ne peut être écrite qu’à un seul endroit. Display for Point ne peut vivre que dans ton crate, puisque personne d’autre ne connaît Point. Resume for Vec<String> aussi, puisque personne d’autre ne connaît Resume. Le conflit n’a pas d’endroit où naître.

Le quatrième cas : E0117

use std::fmt;

impl fmt::Display for Vec<String> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.join(", "))
    }
}
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> orphelin.rs:3:1
  |
3 | impl fmt::Display for Vec<String> {
  | ^^^^^^^^^^^^^^^^^^^^^^-----------
  |                       |
  |                       `Vec` is not defined in the current crate
  |
  = note: impl doesn't have any local type before any uncovered type parameters
  = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
  = note: define and implement a trait or new type instead

Pour voir pourquoi, suppose que ce soit permis. Le crate crate_a écrit cette impl et sépare par des virgules. Le crate crate_b, sans le savoir, écrit la même et sépare par des points-virgules. Ton programme dépend des deux. Que doit afficher println!("{v}") ? Aucune réponse n’est juste, et rustc ne pourrait le découvrir qu’au moment d’assembler le programme, longtemps après que les deux auteurs ont publié. La règle de l’orphelin coupe le problème à la racine : aucun des deux n’a le droit d’écrire cette impl.

La dernière note de rustc donne les deux sorties : define and implement a trait or new type instead.

La sortie : le newtype

struct Liste(Vec<String>);

impl fmt::Display for Liste {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.join(", "))
    }
}

let l = Liste(vec!["a".to_string(), "b".to_string()]);
println!("{l}");
println!("{}", size_of::<Liste>() == size_of::<Vec<String>>());
a, b
true

Liste est un type à toi : le couple (Display, Liste) t’appartient, et lui seul. Le Vec reste dedans, accessible par .0. L’enveloppe a exactement la taille de son contenu : le newtype ne coûte rien à l’exécution, seulement quelques lignes à l’écriture.

Ces lignes sont le vrai prix. Liste n’a plus .len(), .push() ni .iter(). On délègue celles qui gardent le sens (fn len(&self) -> usize { self.0.len() }) et on laisse les autres derrière .0. Implémenter Deref<Target = Vec<String>> pour tout récupérer d’un coup est tentant, mais le type intérieur fuit alors par toutes les méthodes, et le newtype perd ce qui le justifiait.

Les impls génériques couvrent une famille

trait Resume { fn resume(&self) -> String; }

impl<T: Display> Resume for T {
    fn resume(&self) -> String {
        self.to_string().chars().take(5).collect()
    }
}

println!("{}", 3.14159.resume());
println!("{}", "bonjour".resume());
3.141
bonjo

Une seule impl, et tout type qui implémente Display reçoit Resume, y compris les types de la std ou d’autres crates. C’est une blanket impl. La std en est tissée : .to_string() existe sur tout Display parce que la std contient impl<T: Display + ?Sized> ToString for T. Combinée à un trait à toi, elle ajoute des méthodes à des types que tu ne possèdes pas, sans newtype : c’est le patron du trait d’extension.

Le revers : le chevauchement (E0119)

impl<T: Display> Resume for T { … }

impl Display for Point { … }
impl Resume for Point { … }
error[E0119]: conflicting implementations of trait `Resume` for type `Point`
  --> chevauche.rs:17:1
   |
 5 | impl<T: Display> Resume for T {
   | ----------------------------- first implementation here
...
17 | impl Resume for Point {
   | ^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Point`

Point implémente Display, il a donc déjà Resume par l’impl générique. La seconde impl donne deux réponses pour le même couple : c’est exactement ce que la cohérence interdit, que les deux corps fassent ou non la même chose. Rust stable n’a pas de spécialisation, qui laisserait une impl plus précise l’emporter. Une impl générique est donc une promesse sans exception : on resserre la borne, ou on renonce à l’une des deux.

C’est le même E0119 que deux #[from] du même type avec thiserror, et il explique un détail d’anyhow. Écrire « toute erreur se convertit en la mienne » rencontre l’impl réflexive de core, dès que ton type est lui-même une erreur :

impl Error for MonErreur {}

impl<E: Error> From<E> for MonErreur { … }
error[E0119]: conflicting implementations of trait `From<MonErreur>` for type `MonErreur`
  --> from_tout.rs:12:1
   |
12 | impl<E: Error> From<E> for MonErreur {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> From<T> for T;

MonErreur est une Error, donc From<MonErreur> for MonErreur est demandé deux fois. anyhow::Error contourne le problème en n’implémentant pas std::error::Error.

Un T nu derrière un trait étranger (E0210)

trait Forme { fn aire(&self) -> f64; }

impl<T: Forme> fmt::Display for T { … }
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> e0210.rs:5:6
  |
5 | impl<T: Forme> fmt::Display for T {
  |      ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter

Forme est à toi, mais Display ne l’est pas, et T peut désigner n’importe quel type. Un crate qui dépend du tien peut définir Carre, lui implémenter Forme et lui donner son propre Display : ton impl en ferait deux. rustc refuse sans regarder la borne. La sortie est le newtype, en version générique :

struct Affiche<T>(T);

impl<T: Forme> fmt::Display for Affiche<T> { … }

println!("{}", Affiche(Cercle { r: 1.0 }));
aire 3.14

Affiche est à toi, donc Display for Affiche<Carre> ne peut s’écrire nulle part ailleurs que chez toi.

Ce que l’image cache

  • « À toi » se lit au premier niveau. impl Display for Vec<Point> est refusé même si Point est à toi : le type est un Vec, étranger. Il y a une exception : Box, & et &mut sont transparents pour la règle (fundamental), donc impl Display for Box<Point> passe.
  • Le type local peut aussi être un paramètre du trait. impl From<Point> for String est accepté : From<Point> mentionne un type à toi. C’est pourquoi on peut écrire des conversions vers les types de la std.
  • Toute impl publique est une promesse. Ajouter une impl générique à un crate publié peut casser ses utilisateurs, dont une impl se met soudain à chevaucher la tienne. Les impls génériques se décident tôt.
  • Newtype ou trait d’extension. Pour implémenter un trait étranger, il faut un newtype. Pour seulement ajouter des méthodes à un type étranger, un trait à toi suffit (avec une impl générique si besoin), et le type reste le même pour l’appelant.

Pour aller plus loin

The four cases

A trait and a type, each yours or foreign: four combinations, three accepted.

struct Point { x: i32, y: i32 }
trait Resume { fn resume(&self) -> String; }

impl fmt::Display for Point { … }     // foreign trait, your type: yes
impl Resume for Vec<String> { … }     // your trait, foreign type: yes
(1, 2)
1 éléments
                 your type           foreign type
             ┌──────────────────┬──────────────────┐
your trait   │ ✓ Resume  Point  │ ✓ Resume  Vec    │
             ├──────────────────┼──────────────────┤
foreign      │ ✓ Display Point  │ ✕ Display Vec    │  ← E0117
trait        │                  │                  │
             └──────────────────┴──────────────────┘

In the three accepted cases, the impl can only be written in one place. Display for Point can only live in your crate, since nobody else knows Point. So can Resume for Vec<String>, since nobody else knows Resume. The conflict has nowhere to arise.

The fourth case: E0117

use std::fmt;

impl fmt::Display for Vec<String> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.join(", "))
    }
}
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> orphelin.rs:3:1
  |
3 | impl fmt::Display for Vec<String> {
  | ^^^^^^^^^^^^^^^^^^^^^^-----------
  |                       |
  |                       `Vec` is not defined in the current crate
  |
  = note: impl doesn't have any local type before any uncovered type parameters
  = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
  = note: define and implement a trait or new type instead

To see why, suppose it were allowed. The crate crate_a writes this impl and separates with commas. The crate crate_b, unaware, writes the same one and separates with semicolons. Your program depends on both. What should println!("{v}") print? No answer is right, and rustc could only find out when assembling the program, long after both authors published. The orphan rule cuts the problem at the root: neither of them may write that impl.

rustc’s last note gives both ways out: define and implement a trait or new type instead.

The way out: the newtype

struct Liste(Vec<String>);

impl fmt::Display for Liste {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.join(", "))
    }
}

let l = Liste(vec!["a".to_string(), "b".to_string()]);
println!("{l}");
println!("{}", size_of::<Liste>() == size_of::<Vec<String>>());
a, b
true

Liste is a type of yours: the pair (Display, Liste) belongs to you, and only you. The Vec stays inside, reachable through .0. The wrapper has exactly the size of its content: the newtype costs nothing at runtime, only a few lines at writing time.

Those lines are the real price. Liste no longer has .len(), .push() or .iter(). You delegate the ones that keep the meaning (fn len(&self) -> usize { self.0.len() }) and leave the others behind .0. Implementing Deref<Target = Vec<String>> to get everything back at once is tempting, but the inner type then leaks through every method, and the newtype loses what justified it.

Generic impls cover a family

trait Resume { fn resume(&self) -> String; }

impl<T: Display> Resume for T {
    fn resume(&self) -> String {
        self.to_string().chars().take(5).collect()
    }
}

println!("{}", 3.14159.resume());
println!("{}", "bonjour".resume());
3.141
bonjo

A single impl, and every type implementing Display gets Resume, including types from std or other crates. It’s a blanket impl. std is woven with them: .to_string() exists on every Display because std contains impl<T: Display + ?Sized> ToString for T. Combined with a trait of your own, it adds methods to types you don’t own, without a newtype: that’s the extension trait pattern.

The flip side: overlap (E0119)

impl<T: Display> Resume for T { … }

impl Display for Point { … }
impl Resume for Point { … }
error[E0119]: conflicting implementations of trait `Resume` for type `Point`
  --> chevauche.rs:17:1
   |
 5 | impl<T: Display> Resume for T {
   | ----------------------------- first implementation here
...
17 | impl Resume for Point {
   | ^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Point`

Point implements Display, so it already has Resume through the generic impl. The second impl gives two answers for the same pair: exactly what coherence forbids, whether or not both bodies do the same thing. Stable Rust has no specialization, which would let a more precise impl win. A generic impl is therefore a promise without exceptions: you narrow the bound, or give up one of the two.

It’s the same E0119 as two #[from] of the same type with thiserror, and it explains a detail of anyhow. Writing “any error converts into mine” runs into core’s reflexive impl as soon as your type is itself an error:

impl Error for MonErreur {}

impl<E: Error> From<E> for MonErreur { … }
error[E0119]: conflicting implementations of trait `From<MonErreur>` for type `MonErreur`
  --> from_tout.rs:12:1
   |
12 | impl<E: Error> From<E> for MonErreur {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> From<T> for T;

MonErreur is an Error, so From<MonErreur> for MonErreur is requested twice. anyhow::Error sidesteps the problem by not implementing std::error::Error.

A bare T behind a foreign trait (E0210)

trait Forme { fn aire(&self) -> f64; }

impl<T: Forme> fmt::Display for T { … }
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> e0210.rs:5:6
  |
5 | impl<T: Forme> fmt::Display for T {
  |      ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter

Forme is yours, but Display isn’t, and T can be any type. A crate depending on yours can define Carre, implement Forme for it and give it its own Display: your impl would make two. rustc refuses without looking at the bound. The way out is the newtype, in generic form:

struct Affiche<T>(T);

impl<T: Forme> fmt::Display for Affiche<T> { … }

println!("{}", Affiche(Cercle { r: 1.0 }));
aire 3.14

Affiche is yours, so Display for Affiche<Carre> can’t be written anywhere but in your crate.

What the picture hides

  • “Yours” is read at the top level. impl Display for Vec<Point> is refused even though Point is yours: the type is a Vec, foreign. There’s one exception: Box, & and &mut are transparent to the rule (fundamental), so impl Display for Box<Point> passes.
  • The local type can also be a parameter of the trait. impl From<Point> for String is accepted: From<Point> mentions a type of yours. That’s why you can write conversions into std types.
  • Every public impl is a promise. Adding a generic impl to a published crate can break its users, one of whose impls suddenly overlaps yours. Generic impls are decided early.
  • Newtype or extension trait. To implement a foreign trait, you need a newtype. To merely add methods to a foreign type, a trait of your own is enough (with a generic impl if needed), and the type stays the same for the caller.

Going further

Questions fréquentesFrequently asked questions

Que signifie « only traits defined in the current crate can be implemented for types defined outside of the crate » (E0117) ?What does "only traits defined in the current crate can be implemented for types defined outside of the crate" (E0117) mean?

Tu implémentes un trait que tu ne possèdes pas (Display, de la std) pour un type que tu ne possèdes pas (Vec<String>, de la std). Rust exige que le crate qui écrit une impl possède au moins le trait ou le type : c'est la règle de l'orphelin. Correctif : envelopper le type dans un newtype à toi (struct Liste(Vec<String>)) et implémenter le trait pour lui, ou définir ton propre trait.You're implementing a trait you don't own (Display, from std) for a type you don't own (Vec<String>, from std). Rust requires the crate writing an impl to own at least the trait or the type: that's the orphan rule. Fix: wrap the type in a newtype of yours (struct Liste(Vec<String>)) and implement the trait for it, or define your own trait.

Pourquoi Rust impose-t-il la règle de l'orphelin ?Why does Rust enforce the orphan rule?

Pour garantir la cohérence : au plus une impl par couple (trait, type) dans tout le programme. Sans la règle, deux crates sans lien pourraient implémenter Display pour Vec<String> chacun de leur côté, et un programme qui dépend des deux n'aurait aucun moyen de choisir. Avec elle, une impl ne peut vivre que dans le crate du trait ou dans celui du type, et le conflit ne peut pas naître.To guarantee coherence: at most one impl per (trait, type) pair in the whole program. Without the rule, two unrelated crates could each implement Display for Vec<String>, and a program depending on both would have no way to choose. With it, an impl can only live in the trait's crate or the type's crate, and the conflict can't arise.

Le newtype coûte-t-il quelque chose ?Does the newtype cost anything?

Rien à l'exécution : struct Liste(Vec<String>) a exactement la même taille que Vec<String>, vérifié avec size_of. Le coût est à l'écriture : le newtype perd les méthodes du type enveloppé. On délègue celles qui préservent le sens, ou on accède au contenu par .0. Implémenter Deref pour tout récupérer laisse fuir le type intérieur et défait souvent la raison d'être du newtype.Nothing at runtime: struct Liste(Vec<String>) has exactly the same size as Vec<String>, checked with size_of. The cost is at writing time: the newtype loses the wrapped type's methods. You delegate the ones that preserve the meaning, or reach the content through .0. Implementing Deref to get everything back leaks the inner type and often defeats the newtype's purpose.

Pourquoi E0119 « conflicting implementations » avec une impl générique ?Why E0119 "conflicting implementations" with a generic impl?

impl<T: Display> Resume for T donne déjà Resume à tout type qui implémente Display. Si Point implémente Display, il a déjà Resume, et écrire impl Resume for Point en crée une seconde pour le même couple. La cohérence l'interdit, même si les deux impls feraient la même chose. Rust stable n'a pas de spécialisation : il faut resserrer la borne ou renoncer à l'une des deux.impl<T: Display> Resume for T already gives Resume to every type implementing Display. If Point implements Display, it already has Resume, and writing impl Resume for Point creates a second one for the same pair. Coherence forbids it, even if both impls would do the same thing. Stable Rust has no specialization: you must narrow the bound or give up one of the two.

Que signifie E0210 « type parameter `T` must be used as the type parameter for some local type » ?What does E0210 "type parameter `T` must be used as the type parameter for some local type" mean?

Tu implémentes un trait étranger (Display) pour un T nu. T peut désigner n'importe quel type, y compris un type d'un autre crate qui a peut-être déjà son propre Display. rustc refuse sans regarder la borne. Correctif : un type local qui porte le T, struct Affiche<T>(T), puis impl<T: Forme> Display for Affiche<T>.You're implementing a foreign trait (Display) for a bare T. T can be any type, including a type from another crate that may already have its own Display. rustc refuses without looking at the bound. Fix: a local type carrying the T, struct Affiche<T>(T), then impl<T: Forme> Display for Affiche<T>.

RustTraitsCohérenceOrphan ruleE0117Modèle mental

← Tous les articlesAll articles