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)
- Le trait
Displayvient de la std, le typePointest à 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.TheDisplaytrait comes from std, thePointtype is yours. You own one half of the pair: the impl is accepted, and it can't exist anywhere but in your crate. - L'inverse marche aussi.
Resumeest 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.Resumeis your trait,Vec<String>comes from std. You own the trait: you can implement it for any type, even a foreign one. - 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.
- La sortie : un newtype.
Listeest un type à toi qui enveloppe leVec, donc le couple(Display, Liste)t'appartient. Il fait la même taille que leVec: l'enveloppe ne coûte rien à l'exécution.The way out: a newtype.Listeis a type of yours wrapping theVec, so the pair(Display, Liste)belongs to you. It's the same size as theVec: the wrapper costs nothing at runtime.
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 insteadPour 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
trueListe 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
bonjoUne 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 parameterForme 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.14Affiche 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 siPointest à toi : le type est unVec, étranger. Il y a une exception :Box,&et&mutsont transparents pour la règle (fundamental), doncimpl Display for Box<Point>passe. - Le type local peut aussi être un paramètre du trait.
impl From<Point> for Stringest 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
- Volume 5, numéro 03 de The Rust Loop, Orphan rule & blanket impls, qui détaille la cohérence, le newtype face à
Derefet 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, traits et generics (E0369), dyn et vtable (E0038). - The Rust Book : le newtype pour implémenter un trait externe
- La référence : orphan rules
- Index des erreurs : E0117
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 insteadTo 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
trueListe 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
bonjoA 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 parameterForme 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.14Affiche 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 thoughPointis yours: the type is aVec, foreign. There’s one exception:Box,&and&mutare transparent to the rule (fundamental), soimpl Display for Box<Point>passes. - The local type can also be a parameter of the trait.
impl From<Point> for Stringis 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
- Volume 5, issue 03 of The Rust Loop, Orphan rule & blanket impls, which details coherence, the newtype versus
Derefand 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, traits and generics (E0369), dyn and the vtable (E0038). - The Rust Book: the newtype pattern to implement external traits
- The Reference: orphan rules
- Error index: E0117