Alternative Blanket Implementations for a Single Rust Trait

https://news.ycombinator.com/rss Hits: 6
Summary

Serhii Potapov July 01, 2025 #rust #traits #patterns Rust's trait system is famously powerful - and famously strict about avoiding ambiguity. One such rule is that you can't have multiple blanket implementations of the same trait that could potentially apply to the same type. What Is a Blanket Implementation? A blanket implementation is a trait implementation that applies to any type meeting certain constraints, typically via generics. A classic example from the standard library is how From and Into work together: impl<T, U> Into<U> for T where U: From<T>, { fn into(self) -> U { U::from(self) } } Thanks to this, when you implement From<T> for U, you automatically get Into<U> for T. Very ergonomic! The Restriction However, Rust enforces a key rule: no two blanket implementations may overlap - even in theory. Consider: impl<T: TraitA> MyTrait for T { ... } impl<T: TraitB> MyTrait for T { ... } Even if no type currently implements both TraitA and TraitB, the compiler will reject this. The reason? Some type might satisfy both in the future, and that would make the implementation ambiguous. A Real-World Problem While working on Joydb, I ran into this exact problem. I have an Adapter trait responsible for persisting data. In practice, there are two common ways to implement it: A unified adapter that stores all data in a single file (e.g., JSON). In Joydb, this is UnifiedAdapter. A partitioned adapter that stores each relation in a separate file (e.g., one CSV per relation), called PartitionedAdapter. Ideally, users would only need to implement one of those and get the Adapter trait "for free". But Rust won't let me define two conflicting blanket implementations. So... is there a workaround? 馃 The Trait Definitions in Joydb Here are the relevant traits in Joydb: pub trait Adapter { fn write_state<S: State>(&self, state: &S) -> Result<(), JoydbError>; fn load_state<S: State>(&self) -> Result<S, JoydbError>; } pub trait UnifiedAdapter { fn write_state<S: State>(&self, state:...

First seen: 2025-07-04 08:11

Last seen: 2025-07-04 13:12