Questions tagged [orphan-rule]

In Rust, the "orphan rules" forbid you from writing an impl where both the trait and the type are defined in a different crate.

According to Coherence and Orphan Rules in Rust:

The "orphan rules", very roughly speaking, forbid you from writing an impl where both the trait and the type are defined in a different crate. This is meant to:

  • Prevent "dependency hell" problems where multiple crates write conflicting impls, so nobody can ever use both crates in the same program, and the crate authors don't even realize they've created this footgun until someone tries to combine them.

  • Allow crates to add impls for their traits and types without it being considered a breaking change. Without the orphan rules, no crate would ever be allowed to add an impl in a minor or patch version because that would break any program that contained an overlapping impl.

5 questions
3
votes
1 answer

How should library crates be designed around Rust's Orphan Rule?

My understanding of the orphan rule of interest is that: For any impl of a Trait on a Type, either the Trait or the Type must be defined in the same crate as the impl. or equivalently: It is impossible to implement a trait defined in a foreign…
RBF06
  • 2,013
  • 2
  • 21
  • 20
2
votes
2 answers

Multiple `impl`s error while use-ing implementations within separated mods

Digging into the subject of the orphan rule, I ended up with a kind of implementation of a trait by a type both defined outside the implementing crate. But as a result, I now have another question about trait implementation. The following example…
FreD
  • 393
  • 2
  • 12
2
votes
1 answer

Is there a way to design a trait that allows its implementation by any type even if the implementer owns neither the type nor the trait?

In general case, it is not possible to implement in crate C1 a trait defined in C2 for a Type defined in crate C3, being assumed that C1, C2, C3 are different But is there a trick to designing a trait on purpose, so that such implementations are…
FreD
  • 393
  • 2
  • 12
1
vote
0 answers

Implementing a foreign trait for all implementors of a local trait in rust

I have some local types, say struct A; struct B; which all implement a local trait MyTrait: pub trait MyTrait { } impl MyTrait for A { } impl MyTrait for B { } Now I want to implement a standard library trait for both A and B,…
Einliterflasche
  • 473
  • 6
  • 18
0
votes
0 answers

How can I implement generic conversion from my type to any type with a bound?

I am trying to implement the conversion from my type to any type that can be converted from u32. I tried impl From for T where u32: Into by that apparently breaks the orphan rule. As well as impl Into for MyType where u32:…
Simon
  • 860
  • 7
  • 23