Orphan Rule

When you implement a trait, either the trait or the type must be new in the current crate. This is called the orphan rule. It helps Rust ensure that trait implementations are unique.

Your code can’t impl Write for u8, because both Write and u8 are defined in the standard library. If Rust let crates do that, there could be multiple implementations of Write for u8, in different crates, and Rust would have no reasonable way to decide which implementation to use for a given method call.

Generic traits get a special dispensation when it comes to the orphan rule: you can implement a foreign trait for a foreign type, so long as one of the trait’s type parameters is a type defined in the current crate. If you’ve defined WindowSize yourself, you can implement Mul<WindowSize> for f64, even though you didn’t define either Mul or f64. These implementations can even be generic, such as impl<T> Mul<WindowSize> for Vec<T>. This works because there’s no way any other crate could define Mul<WindowSize> on anything, and thus no way a conflict among implementations could arise. This is how crates like nalgebra define arithmetic operations on vectors.

Bringing Traits into Scope

The trait itself must be in scope in order to use its methods.

Rust has this rule because you can use traits to add new methods to any type—even standard library types like u32 and str. Clearly, this could lead to naming conflicts. Two different crates might extend the same type, let’s say, u32, using extension trait by implementing the trait method in each crate respectively. If the trait is not in scope, Rust would have no reasonable way to decide which implementation to use for a given method call. But since Rust makes you import the traits you plan to use, crates are free to take advantage of this superpower. However, if both of the traits are imported at the same time, you will get a conflict.

To get a conflict, you’d have to import two traits that add a method with the same name to the same type. This is rare in practice. (If you do run into a conflict, you can spell out what you want using fully qualified method syntax.)

The reason Clone and Iterator methods work without any special imports is that they’re always in scope by default: they’re part of the standard prelude, names that Rust automatically imports into every module. In fact, the prelude is mostly a carefully chosen selection of traits.