In Rust, may your crate implement its own trait for `String`, a std trait for its own struct, and `std::fmt::Display` for `Vec<u8>`?
answer
- who defined the trait, who defined the type
- std counts as another crate
- at least one side must be yours
- E0117 for foreign trait on foreign type
basics
~20 sYes, yes, no. Rust's orphan rule lets a crate implement a trait for a type only when the trait or the type is defined in that crate; Display and Vec<u8> both come from std, so rustc rejects that impl with E0117.
solid answer
~40 sThe first two are fine and the third is not. Rust's **orphan rule** allows `impl Trait for Type` only when the trait or at least one type in the impl is defined in the current crate. Your own trait on `String` is an extension trait, and `Display` on your own struct is everyday Rust. `impl fmt::Display for Vec<u8>` implements a std trait for a std type, so rustc stops with E0117, "only traits defined in the current crate can be implemented for types defined outside of the crate". The rule protects **coherence**: across a whole program there is at most one impl of a trait for a type, so two crates can never ship clashing impls. The usual way out is a local wrapper struct or a trait of your own.
code
rust · 26 linesuse std::fmt;
// A trait defined in this crate...
trait Shout {
fn shout(&self) -> String;
}
// ...may be implemented for a type from std.
impl Shout for String {
fn shout(&self) -> String {
self.to_uppercase() + "!"
}
}
// A std trait may be implemented for a type defined in this crate.
struct Celsius(f64);
impl fmt::Display for Celsius {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:.1}°C", self.0)
}
}
fn main() {
println!("{} {}", String::from("hot").shout(), Celsius(36.6));
}go deeper
Recall the one-line rule: you may implement a trait for a type only if your crate defines the trait or the type, and std counts as another crate.
Explain that the rule protects coherence, one impl per trait and type across the program, and show the two fixes rustc's note names: a local trait or a wrapper type.
Be ready for the edge cases: a local type as a trait parameter, such as From<Celsius> for f64, is accepted, while Vec<Celsius> as the Self type is not.
Frame the rule as what makes dependency upgrades safe: because only the owning crate can write an impl, adding an impl upstream cannot collide with a downstream one.
## The rule rustc applies Rust lets a crate write `impl Trait for Type` only when it owns at least one side of that pair. The Rust Reference states the **orphan rule** as: a trait implementation is allowed only if either the trait or at least one of the types in the implementation is defined in the current crate. An impl of a **foreign trait** (defined in another crate) for a **foreign type** (also defined in another crate) is called an *orphan*, and rustc rejects it with **E0117**. "Another crate" includes the standard library. `std`, `core` and `alloc` are crates like any other dependency, so `String`, `Vec<T>`, `SystemTime`, `Display` and `Debug` are all foreign to the code you write. ## The three cases in the question | impl | trait defined in | type defined in | result | |---|---|---|---| | `impl Shout for String` | your crate | std | accepted | | `impl fmt::Display for Celsius` | std | your crate | accepted | | `impl fmt::Display for Vec<u8>` | std | std | E0117 | - **Your trait for a std type.** This is how *extension traits* work: you define a trait with the methods you want and implement it for `String`, `u64` or any other type. Code in other modules brings the trait into scope with `use` before calling its methods. - **A std trait for your type.** Everyday Rust: `Display`, `Debug`, `Default` or `From` for your own structs and enums. - **A std trait for a std type.** The orphan case. Neither side belongs to you, so rustc refuses the impl, whatever the method bodies say. Locality is decided by where the outer type is **defined**. `Vec<Celsius>` is still a `Vec`, defined in std, so placing your own type inside it does not make it local. A type alias such as `type Bytes = Vec<u8>;` does not help either: an alias is only another name for the same foreign type. Hiding the impl inside a private module changes nothing, because the module is still part of the same crate and the trait and type are still foreign. ## Why Rust insists on it The orphan rule exists to protect **coherence**: for a given trait and type, the whole program contains at most one impl, so every method call and every generic bound resolves to exactly one piece of code. Picture the language without the rule: 1. Two unrelated libraries each write `impl Display for Vec<u8>`, one printing hex and one printing a byte count. An application that depends on both now has two candidate impls and nothing to choose between them. 2. A later std release adds its own `impl Display for Vec<u8>`. Every crate that had written one stops compiling after a toolchain update. The Reference makes the same point: without the restriction, adding or updating a dependency could break compilation through conflicting impls. Requiring the impl to live in the crate that defines the trait or the type means two unrelated crates can never both write it. ## Reading E0117 The message is long but specific: - the headline: "only traits defined in the current crate can be implemented for types defined outside of the crate"; - a label under the type, such as "`Vec` is not defined in the current crate"; - a closing note, "define and implement a trait or new type instead", which names the two standard fixes. E0117 is a hard error, not a lint, so no attribute switches it off. ## What to do instead 1. **Define a trait of your own** when you only need extra methods on the foreign type, as `Shout` does for `String` in the example. 2. **Wrap the foreign type** in a local tuple struct, for example `struct Bytes(Vec<u8>);`, and implement the foreign trait for the wrapper. The Rust Book notes there is no run-time penalty for this; the cost is that the wrapper does not have the inner type's methods until you forward them. 3. **Ask the crate that owns the trait or the type** to provide the impl. Many libraries ship impls of popular third-party traits behind an optional feature for exactly this reason. Which fix fits depends on what you need: new behaviour you name yourself (a local trait), or a foreign trait that some other code expects, such as `Display` for `{}` formatting (a wrapper).
- If `Celsius` is your own type, may you write `impl fmt::Display for Vec<Celsius>`?No. Locality depends on where the outer type is defined, and `Vec` is defined in std; a local type as a type argument does not change that. rustc rejects it with E0117. Wrap the vector, for example `struct Readings(Vec<Celsius>);`, and implement `Display` for `Readings`.
- Why can your own trait be implemented for `String` without any risk of clashing with another crate?Another crate cannot write that impl: to it, both your trait and `String` are foreign, so the orphan rule blocks it, and std cannot name your trait at all. Your crate is the only place the pair can be implemented, so coherence holds.
- The orphan rule forbids implementing any std trait in your own crate.
- Putting your type inside it, as in Vec<MyType>, makes the type local.
- A type alias like type Bytes = Vec<u8> makes the impl legal.
- Importing the trait with use makes it count as local.
- E0117 is a lint you can silence with an allow attribute.