Extension traits
An extension trait adds methods to a type you do not own. You declare the trait, implement it for the foreign type, and callers import the trait to see the methods.
Detailed Explanation
You cannot write impl Vec<u8> { fn hex(&self) -> String } in your crate. You do not own Vec. You can write trait Hex { fn hex(&self) -> String; } impl Hex for [u8] { ... } and then use crate::Hex; bytes.hex(). The method appears only when the trait is in scope. That is an extension trait.
This is how the ecosystem adds behaviour without wrapper types. itertools extends Iterator. anyhow extends Result with .context(). Your crate can extend str with domain helpers. The orphan rule is satisfied because you own the trait.
Keep extension traits small and well named. A trait called Utils that adds twelve unrelated methods to str is a dumping ground. A trait called HexEncode with one method is discoverable. Document that callers must import it; the compiler error "no method named hex" is otherwise mysterious.
Coherence still applies. You cannot impl Hex for [u8] in two crates the binary uses if both traits are in scope and have the same method name — the call becomes ambiguous. Use distinct names. Do not implement a foreign extension trait for a foreign type.
When you write an extension trait: a method that belongs on a std type for your domain, or a crate of extras (itertools). When you write a newtype: you need a different type, not just a method. When you write a free function: the method syntax is not worth a trait.
Export the trait next to the type it extends, or from the crate root, and mention the import in the rustdoc of the method if rustdoc lets you. A method that only appears after a glob import will be rediscovered as a compiler error by every new contributor. One-line rustdoc on the trait itself ("import Hex to call .hex() on byte slices") pays for itself.
Code Examples
trait Hex {
fn hex(&self) -> String;
}
impl Hex for [u8] {
fn hex(&self) -> String {
self.iter().map(|b| format!("{b:02x}")).collect()
}
}
fn main() {
println!("{}", [0x0d, 0xad].hex()); // prints: 0dad
}Common Gotchas
The trait must be in scope
`bytes.hex()` fails with "no method named hex" until `use ...Hex`. Re-export the trait from the crate root if it is part of the API.
You still cannot impl a foreign trait for a foreign type
An extension trait works because you own the trait. `impl Serialize for Vec<u8>` in your crate is still illegal.
Name collisions are ambiguous
Two extension traits with `fn hex` and both imported will not compile at the call. Use UFCS or rename.
Implement for the unsized type when you can
`impl Hex for [u8]` covers `Vec<u8>`, `&[u8]`, and arrays via deref/coercion more often than `impl Hex for Vec<u8>`.