rust-polymorphismlisted
Install: claude install-skill takurot/rust-skills-comprehensive
# Rust Polymorphism
`rust-patterns` covers "accept generics, return concrete types" and trait objects briefly.
This skill goes deeper on the actual decisions: generics vs `dyn`, why/how to port an
inheritance-shaped design, and controlling who can extend a trait.
## The orphan rule (why you can't `impl` any trait for any type)
Rust forbids implementing a trait for a type when **neither** the trait nor the type is
"local" to your crate — otherwise two crates could each define a conflicting impl of the same
foreign trait for the same foreign type, and the whole ecosystem would have no way to resolve
which one applies.
```rust
// crate `mycoolnewdb`, depends on `database-traits` (defines DbConnection)
// and `postgresql-bindings` (defines PostgresqlConn) — neither is local here.
impl DbConnection for PostgresqlConn {} // ❌ orphan rule violation
```
If you hit `error[E0117]: only traits defined in the current crate can be implemented for
types defined outside of the crate`, the fix is one of:
- Define a **newtype wrapper** around the foreign type in your crate (now the type is local)
and implement the foreign trait for the wrapper instead.
- Define your **own trait** (now the trait is local) with the behavior you need, and implement
it for the foreign type directly.
- If you control one of the two crates, move the trait or type there instead.
## Generics vs `dyn Trait` — decision guide
Both are ways to write one function/type that works across multiple concrete types